Using fprintf to Write Formatted Output to a File in C programming
fprintf
to Write Formatted Output to a File in CUsing fprintf
to Write Formatted Output to a File in C
The fprintf
function in C is used to write formatted output to a file. It works similarly to printf
, but instead of printing to the standard output (console), it writes the formatted string to a file stream.
Syntax
The syntax for fprintf
is as follows:
int fprintf(FILE *stream, const char *format, ...);
Where:
stream
is a pointer to aFILE
object that identifies the output stream (e.g., a file).format
is the format string that specifies how subsequent arguments are formatted....
represents the additional arguments that are formatted according to theformat
string.
Example Code
#include <stdio.h>
int main() {
FILE *file = fopen("output.txt", "w");
int age = 25;
float height = 1.80;
if (file != NULL) {
// Write formatted data to the file
fprintf(file, "Age: %d years\nHeight: %.2f meters\n", age, height);
fclose(file); // Close the file after writing
printf("Data written to output.txt\n");
} else {
printf("Error opening file.\n");
}
return 0;
}
In this example:
FILE *file = fopen("output.txt", "w");
opens a file namedoutput.txt
for writing. If the file does not exist, it will be created.fprintf(file, "Age: %d years\nHeight: %.2f meters\n", age, height);
writes the formatted string to the file, including the values ofage
andheight
.fclose(file);
closes the file after writing to ensure all data is saved and resources are freed.printf("Data written to output.txt\n");
confirms that the data has been successfully written to the file.
Key Points
- File Handling: Always check if the file is successfully opened before using
fprintf
. Handle potential errors if the file cannot be opened. - Format Specifiers: Use format specifiers in
fprintf
to format data as needed (e.g.,%d
for integers,%f
for floating-point numbers). - Buffer Management: Ensure the data being written matches the format specifiers used in
fprintf
.
Note: The
fprintf
function is useful for creating formatted text files and logs. Make sure to handle file errors and always close the file after writing.
Comments
Post a Comment