C fprintf
Created By: chatGPT
The
fprintf
function in C is part of the stdio.h library, which allows you to send formatted output to a specified stream. Unlike printf, which writes to standard output (stdout), fprintf
can write to files or other output streams. This flexibility makes it a powerful tool when working with file I/O in C. You can customize the output format by using format specifiers, similar to how you would in printf
.#include <stdio.h>
int main() {
FILE *file;
file = fopen("output.txt", "w"); // open file for writing
if (file == NULL) {
perror("Error opening file");
return -1;
}
int age = 25;
float height = 5.9;
const char *name = "John Doe";
fprintf(file, "Name: %s\n", name);
fprintf(file, "Age: %d\n", age);
fprintf(file, "Height: %.1f\n", height);
fclose(file); // close the file
return 0;
}
In this example, we first include the necessary header for file operations. We use
fopen
to open a file named output.txt in write mode. If the file is successfully opened, we then use fprintf
to write formatted data, including a string, an integer, and a floating-point number. Each call to fprintf
can use format specifiers like %s
for strings, %d
for integers, and %.1f
for floating-point numbers, allowing you to control how the values are represented.fprintf(file, "Some text: %s\n", someString); // String output
fprintf(file, "Value: %d\n", someInteger); // Integer output
fprintf(file, "Measure: %.2f\n", someFloat); // Float output
It's also crucial to always close the file with
fclose
after you're done writing to ensure all data is flushed and resources are released. If the file cannot be opened, handle the error appropriately, as shown in the example. Remember, proper error handling is a key aspect of writing reliable code.if (file == NULL) {
perror("Error opening file");
return -1;
}
// Write to the file
fclose(file); // Always close the file