Formatted file output with fprintf
What you'll learn: How to save structured data to a text file using a function that works exactly like printf.
Your file is a blank canvas
Up to this point, you have likely used printf to display information on your screen. When you use printf, you provide a "format string" with placeholders like %d for integers or %f for decimals, and the computer fills them in.
Writing to a file works exactly the same way. The only difference is that instead of sending the text to the terminal, you send it to a file pointer. Think of a file pointer (FILE *) like a dedicated pipe leading to a specific document on your hard drive. The fprintf function (the 'f' stands for 'file') is the tool that pushes formatted text through that pipe.
Using fprintf
To use fprintf, you need three things: a pointer to a file that is open for writing, a format string, and the variables you want to save.
If you know how to use printf, you already know 90% of fprintf. The only change is that the file pointer becomes the very first argument.
#include <stdio.h>
int main() {
// Open a file for writing ("w")
FILE *fptr = fopen("hero_stats.txt", "w");
if (fptr == NULL) {
return 1; // Error opening file
}
char name[] = "Arthur";
int level = 15;
float health = 98.5;
// fprintf works just like printf, but needs the file pointer first
fprintf(fptr, "Character: %s\n", name);
fprintf(fptr, "Level: %d\n", level);
fprintf(fptr, "HP: %.1f\n", health);
// Always close the pipe when finished
fclose(fptr);
return 0;
}
Why this is useful
Imagine you are creating a high-score system for a game. You don't just want to dump raw numbers into a file; you want them to be readable. fprintf allows you to create organized logs, CSV-style reports, or simple save files that humans can open and read in a standard text editor like Notepad.
It handles all the heavy lifting of converting your binary data (like the bits of an integer) into human-readable characters automatically. If you change a %d to a %04d, fprintf will even add leading zeros for you, making your file output look professional and consistent.
Key takeaway
fprintf is a version of printf that directs formatted text into a file instead of the console.