How to Use fprintf in C: Syntax and Examples
In C,
fprintf is used to write formatted text to a file stream. You provide the file pointer, a format string, and the values to print, similar to printf but directed to a file instead of the console.Syntax
The basic syntax of fprintf is:
FILE *stream: The file pointer where output is written.const char *format: A string that specifies how to format the output....: The values to be formatted and written according to the format string.
c
int fprintf(FILE *stream, const char *format, ...);
Example
This example shows how to open a file, write formatted text using fprintf, and then close the file.
c
#include <stdio.h> int main() { FILE *file = fopen("output.txt", "w"); if (file == NULL) { perror("Failed to open file"); return 1; } int age = 25; double height = 5.9; fprintf(file, "Age: %d years\nHeight: %.1f feet\n", age, height); fclose(file); return 0; }
Common Pitfalls
Common mistakes when using fprintf include:
- Not checking if the file was opened successfully before writing.
- Using incorrect format specifiers that don't match the data types.
- Forgetting to close the file with
fclose, which can cause data loss.
c
#include <stdio.h> int main() { FILE *file = fopen("output.txt", "w"); if (file == NULL) { perror("Failed to open file"); return 1; } // Wrong: Using %d for a double value double height = 5.9; // fprintf(file, "Height: %d feet\n", height); // Incorrect // Correct usage: fprintf(file, "Height: %.1f feet\n", height); fclose(file); return 0; }
Quick Reference
fprintf writes formatted output to a file stream. Use format specifiers like %d for integers, %f for floats, and %s for strings. Always check if the file opened successfully and close it after writing.
| Format Specifier | Description |
|---|---|
| %d | Integer |
| %f | Floating-point number |
| %.1f | Floating-point with 1 decimal place |
| %s | String |
| %c | Character |
| %ld | Long integer |
Key Takeaways
Use fprintf to write formatted text to files by passing a file pointer and format string.
Always check if the file opened successfully before writing with fprintf.
Match format specifiers correctly to the data types to avoid errors.
Close the file with fclose to ensure all data is saved properly.
fprintf works like printf but directs output to a file instead of the console.