What is fprintf() and fscanf() in C language - fprintf() and fscanf() in C language - fprintf() and fscanf() - File handling
What is fprintf() and fscanf() in C language?
fprintf() and fscanf() are functions in the C standard
input/output library (<stdio.h>) that provide a way to perform formatted
input and output to files, respectively. These functions are similar to printf()
and scanf(), but instead of interacting with the standard input/output
(keyboard and screen), they work with files.
1. fprintf(): Formatted Output to a File
Description: fprintf() is used to write formatted data to a
file. It allows you to write data to a file in a specified format, similar to
how printf() works for the standard output.
Syntax:
int fprintf(FILE *stream, const char *format, ...);
Parameters:
stream: A pointer to the file where the data is to be
written.
format: A format string that defines the layout of the
output.
...: Additional arguments corresponding to the format
specifier in the format string.
Example:
#include <stdio.h>
int main() {
FILE *filePointer;
filePointer =
fopen("example.txt", "w");
if (filePointer !=
NULL) {
fprintf(filePointer, "This is a
formatted output: %d\n", 42);
fclose(filePointer);
} else {
printf("Error opening the file.\n");
}
return 0;
}
2. fscanf(): Formatted Input from a File
Description: fscanf() is used to read formatted data from a
file. It allows you to read data from a file in a specified format, similar to
how scanf() works for the standard input.
Syntax:
int fscanf(FILE *stream, const char *format, ...);
Parameters:
stream: A pointer to the file from which the data is to be
read.
format: A format string that defines the expected layout of
the input.
...: Additional pointers to variables where the read values
will be stored, corresponding to the format specifier in the format string.
Example:
#include <stdio.h>
int main() {
FILE *filePointer;
filePointer =
fopen("example.txt", "r");
if (filePointer !=
NULL) {
int value;
fscanf(filePointer, "This is a formatted output: %d\n",
&value);
printf("Read value: %d\n", value);
fclose(filePointer);
} else {
printf("Error opening the file.\n");
}
return 0;
}
In both examples, the FILE pointer (filePointer) is used to
specify the file where the data is to be written or read. The format string in
fprintf() and fscanf() contains format specifiers that define the expected
input or output format, and additional arguments (variables) correspond to
these specifiers. These functions provide a way to perform input and output
operations with a structured and formatted approach when dealing with files.
Comments
Post a Comment