fprintf c
Explanation of fprintf
in C
The fprintf
function in C is used to write formatted output to a file stream. It is similar to the printf
function, but instead of printing to the console, it writes the output to a file. The general syntax of the fprintf
function is as follows:
int fprintf(FILE stream, const char format, ...);
stream
: A pointer to the file stream where the output will be written.format
: A string that specifies the format of the output....
: Additional arguments that correspond to the format specifiers in the format string.
The fprintf
function returns the number of characters written to the file stream, or a negative value if an error occurs.
Here's an example usage of the fprintf
function:
#include <stdio.h>
int main() {
FILE *file = fopen("output.txt", "w");
if (file == NULL) {
printf("Failed to open file\n");
return 1;
}
int num = 42;
fprintf(file, "The answer is %d\n", num);
fclose(file);
return 0;
}
In this example, the fprintf
function is used to write the string "The answer is 42" to a file named "output.txt". The %d
format specifier is used to print the value of the num
variable.
Please note that the example provided is a simplified demonstration and does not include error handling for brevity.