The fscanf and fprintf functions
The fscanf
and fprintf
functions are part of the standard input/output library in the C programming language.
The fscanf
function is used to read formatted data from a file or from the standard input stream. It takes in two arguments: the first argument is the file pointer to the input stream, and the second argument is a format string that specifies the format of the input to be read. fscanf
returns the number of input items successfully matched and assigned.
The fprintf
function is used to write formatted output to a file or to the standard output stream. It takes in two arguments: the first argument is the file pointer to the output stream, and the second argument is a format string that specifies the format of the output to be written. fprintf
returns the number of characters written.
Both fscanf
and fprintf
work in a similar way to the scanf
and printf
functions, but instead of reading from or writing to the standard input/output stream, they read from or write to a specified file.
These functions are commonly used for reading input from a file, processing the data, and then writing the processed data to another file or to the standard output. They provide a convenient way to handle formatted input and output in C programs.
Here is an example that demonstrates the usage of fscanf
and fprintf
functions:
#include <stdio.h>
int main() {
FILE *input_file = fopen("input.txt", "r");
FILE *output_file = fopen("output.txt", "w");
int number;
fscanf(input_file, "%d", &number);
fprintf(output_file, "The number is: %d\n", number);
fclose(input_file);
fclose(output_file);
return 0;
}
In this example, the program opens an input file called "input.txt" for reading and an output file called "output.txt" for writing. It then uses fscanf
to read an integer from the input file and fprintf
to write the number to the output file.
Please let me know if you need further assistance!