fprintf() is a standard library function used to write formatted output to a specified file or output stream.
- It works like printf(), but writes the output to a file instead of the console.
- It supports format specifiers such as %d, %f, %c, and %s for formatted file output.
#include <stdio.h>
int main() {
FILE *fp = fopen("data.txt", "w");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
int id = 101;
float salary = 45000.50;
char name[] = "Rahul";
fprintf(fp, "ID: %d\n", id);
fprintf(fp, "Name: %s\n", name);
fprintf(fp, "Salary: %.2f\n", salary);
fclose(fp);
printf("Data written successfully.\n");
return 0;
}
Output
Data written successfully.
Syntax
int fprintf(FILE *stream, const char *format, ...);
Parameters:
- stream: Pointer to the file where the output will be written.
- format: Format string containing text and format specifiers.
- ... : Additional values to be written to the file.
Return Value:
- Returns the number of characters written on success.
- Returns a negative value if an error occurs.
Advantages
fprintf() is widely used for writing formatted output to files in C programs.
- It writes formatted data directly to a file instead of displaying it on the console.
- It supports format specifiers such as %d, %f, %c, and %s for formatted output.
- It is useful for creating logs, reports, configuration files, and storing program output.
printf() Vs fprintf()
printf() | fprintf() |
|---|---|
Writes formatted output to the standard output (stdout). | Writes formatted output to a specified file stream. |
| Output is displayed on the console. | Output is written to a file or any valid output stream. |
Does not require a FILE pointer. | Requires a valid FILE pointer. |
Syntax: printf(format, ...); | Syntax: fprintf(FILE *stream, format, ...); |
| Mainly used for displaying output to the user. | Mainly used for writing formatted data to files. |