In C Language, "fprintf()" is a function used to write formatted data to a file.
It's part of the standard input/output library defined in the "stdio.h" header file.
It supports various format specifiers like %f, %d, %s, etc., allowing us to format the output per our requirements.
It takes a format string followed by variable number of arguments that correspond to the format specify in the format string.
"fprintf()" function is more efficient than writing characters one by one using "fputc()" function when dealing with formatted output.
"fprintf()" function works similarly to "printf()" function, but instead of printing to the standard output (usually the console), it prints to a specified file stream data. "printf()" function can write different data types to a file, making it versatile for various output requirements.
File Output: It enables us to write formatted data to files and generates reports, logs, or any other text-based output.
Formatting Control: `printf()`, `fprintf()` support various format specifiers, including formatting numbers, strings, and other data types.
#include <stdio.h> int fprintf(FILE *stream, const char *format, ...);
stream: This is a pointer to the file stream where we want to write the formatted output. It should be obtained by opening a file using "fopen()" or be one of the standard streams like "stdout", "stderr", etc
"format": This is a C string that specifies the format of the output. It can contain format specifiers like "%d", "%f", "%s", etc. which are replaced by the values specified after the format parameter.
"...": This represents the additional arguments that correspond to the format specifiers in the format string.
#include <stdio.h> int main() { FILE *file_ptr; char filename[] = "example.txt"; // Open a file for writing file_ptr = fopen(filename, "w"); if (file_ptr == NULL) { printf("Error opening the file.\n"); return 1; // Return error status } // Write formatted data to the file int num = 10; float f_num = 3.14; fprintf(file_ptr, "Integer: %d, Float: %.2f\n", num, f_num); // Close the file stream using fclose function fclose(file_ptr); return 0; // Return success status }
Open a file named "example.txt" in writing mode using "fopen()" function.
Formatted data is written to the file using "fprintf()". In this case, we print an integer "%d" and a floating-point number "%.2f" to the file.
Finally, we close the file stream using "fclose()" function.
After running this program, the "example.txt" file will be created (or overwritten if it already exists) with the formatted data written to it.