A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
fprintf is printf with a FILE* as its first argument. Everything you know about format specifiers, width, and precision applies identically. The difference is where the output goes and how you detect failure. printf writes to stdout, which is line-buffered to a terminal. fprintf can write to any stream, and that stream might be fully buffered, unbuffered, or connected to a network socket. Buffering behavior affects when your data actually hits disk.
#include <stdio.h>int main(void) {FILE *fp = fopen("report.txt", "w");if (fp == NULL) {perror("fopen");return 1;}fprintf(fp, "=== Monthly Report ===\n");fprintf(fp, "%-15s %8s %8s\n", "Name", "Score", "Grade");fprintf(fp, "%-15s %8d %8.1f\n", "Alex", 95, 3.8);fprintf(fp, "%-15s %8d %8.1f\n", "Jordan", 87, 3.2);fprintf(fp, "%-15s %8d %8.1f\n", "Sam", 92, 3.6);int result = fclose(fp);if (result != 0) {perror("fclose");return 1;}printf("Report written.\n");return 0;}
fprintf returns the number of characters written, or a negative value on error. In production code writing to files that might fill up, disconnect, or become read-only, you check that return value. Ignoring it means your program believes it logged data that was never actually written.
#include <stdio.h>int main(void) {FILE *fp = fopen("/nonexistent_dir/log.txt", "w");if (fp == NULL) {perror("fopen");return 1;}int written = fprintf(fp, "This will fail\n");if (written < 0) {perror("fprintf");fclose(fp);return 1;}fclose(fp);return 0;}
In this case fopen catches the problem before fprintf ever runs. But if the disk fills up mid-write, fopen succeeds and fprintf fails. That is when the return value check matters. Also check fclose: it flushes the buffer, and the flush can fail even if every fprintf succeeded.
fprintf(stderr, ...) writes to the standard error stream. This is unbuffered by default, so your error messages appear immediately even if stdout is redirected to a file. Use it for diagnostics, warnings, and error messages. Keep stdout clean for actual program output so users can pipe it without getting your debug noise mixed in.
fprintf is the workhorse of file output in C. Log files, config files, CSV exports, report generators. They all use it. The discipline is in checking return values and understanding buffering. Next: fputs, which writes a string without formatting overhead.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.