Purpose of the fscanf Function in C programming
fscanf
Function in CPurpose of the fscanf
Function in C
The fscanf
function in C is used for formatted input. It reads data from a file or standard input and parses it according to a specified format. This function is similar to scanf
, but instead of reading from the standard input (keyboard), it reads from a file or other input stream.
Syntax
The syntax for fscanf
is as follows:
int fscanf(FILE *stream, const char *format, ...);
Where:
stream
is a pointer to aFILE
object that identifies the input stream (e.g., a file).format
is the format string that specifies how the input data should be parsed....
represents additional pointers to variables where the parsed data will be stored.
Example Code
#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "r");
int age;
float height;
if (file != NULL) {
fscanf(file, "%d %f", &age, &height);
fclose(file);
printf("Age: %d\n", age);
printf("Height: %.2f\n", height);
} else {
printf("Error opening file.\n");
}
return 0;
}
In this example:
FILE *file = fopen("data.txt", "r");
opens a file nameddata.txt
for reading.fscanf(file, "%d %f", &age, &height);
reads an integer and a floating-point number from the file and stores them in theage
andheight
variables, respectively.fclose(file);
closes the file after reading.printf("Age: %d\n", age);
andprintf("Height: %.2f\n", height);
print the values ofage
andheight
to the standard output.
Key Points
- File Input:
fscanf
can read formatted data from files or standard input streams. - Format Specifiers: Use format specifiers in the
format
string to parse different types of data (e.g.,%d
for integers,%f
for floating-point numbers). - Error Handling: Always check if the file was successfully opened before using
fscanf
, and handle potential read errors appropriately.
Note: Be cautious with
fscanf
as improper format specifiers or mismatched data types can lead to unexpected behavior or errors.
Comments
Post a Comment