In C Language, "fscanf()" is a function used to read formatted data from a file.
It's part of the standard input/output library "stdio.h".
"fscanf()" works similarly to "scanf()", but instead of reading from the standard input (usually the console), it reads from a specified file stream.
`fscanf()` function returns the number of input items successfully matched and assigned, or EOF (End of File) if the end of the file is reached or an error encountered.
File Input: `fscanf()` enables reading formatted data from files, allowing us to parse structured data stored in text files.
Formatting Control: `scanf()` and `fscanf()` supports various format specifiers for reading different types of data, including integers, floating-point numbers, strings, and other data types.
Alice Collin 32 Edward Collin 34
#include <stdio.h> int fscanf(FILE *stream, const char *format, ...);
stream: This is a pointer to the file stream from which we want to read the formatted input. It should be obtained by opening a file using "fopen()" or be one of the standard streams like "stdin", "stdout", etc.
format: This is a C string that specifies the format of the input to be read. It should contain format specifiers like "%d", "%f", "%s", etc., which indicate the type and format of the data expected to be read from the file.
"...": This represents the additional arguments that correspond to the variables where the read values will be stored, according to the format specifiers in the format string.
#include <stdio.h> int main() { FILE *file_ptr; char filename[] = "example.txt"; char name[50]; int age; // Open the file for reading file_ptr = fopen(filename, "r"); if (file_ptr == NULL) { printf("Error opening the file.\n"); return 1; // Return error status } // Read data from the file while (fscanf(file_ptr, "%s %d", name, &age) == 2) { printf("Name: %s, Age: %d\n", name, age); } // Close the file stream fclose(file_ptr); return 0; // Return success status }
We open a file named "example.txt" for reading using "fopen()".
We use "fscanf()" in a loop to read formatted data from the file. The format specifier "%s" reads a string "name", and "%d" reads an integer "age".
The loop continues until "fscanf()" returns a value other than 2, indicating that either the end of the file has been reached or there was a format mismatch.
Inside the loop, we print the "name" and "age" of each "employee" read from the file.
Finally, we close the file stream using "fclose()".
When we run the above program, it will read the data from "example.txt" and print the "names" and "ages" of the "employees" listed in the file.
Make sure that the format specifiers in the "fscanf()" calls match the format of the data in the file. Otherwise, the behaviour of the program may be unpredictable.