What is the purpose of the fscanf () function? Give an example of it’s uses
The correct answer and explanation is:
The purpose of the fscanf()
function in C is to read formatted input from a file. It works similarly to scanf()
, but instead of reading input from the standard input (keyboard), it reads from a file pointer. This function is part of the standard C library, and it is used when a program needs to extract structured data from a file.
Syntax:
int fscanf(FILE *stream, const char *format, ...);
stream
: A pointer to aFILE
object that identifies the input stream.format
: A format string that specifies how the input should be read....
: Variables where the extracted values will be stored.
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "r");
int id;
char name[20];
float score;
if (file != NULL) {
fscanf(file, "%d %s %f", &id, name, &score);
printf("ID: %d\nName: %s\nScore: %.2f\n", id, name, score);
fclose(file);
} else {
printf("Error opening file.\n");
}
return 0;
}
Suppose data.txt
contains:
101 John 89.5
Output:
ID: 101
Name: John
Score: 89.50
Explanation (300 words):
The fscanf()
function is designed for formatted input from files. It is especially useful when the content of a file is structured in a predictable way, such as a list of records where each line follows a specific pattern (e.g., ID, name, and score). This function reads data directly into variables, converting them into the appropriate types, such as integers, strings, or floating-point numbers, based on the format specifiers provided.
When fscanf()
is called, it reads from the file stream sequentially, matching the input to the format string. Format specifiers like %d
, %s
, and %f
are used for integers, strings, and floats, respectively. The function stores the read values into the variables provided via pointers.
This allows developers to avoid manually parsing strings and converting types, making data handling more efficient and less error-prone. However, it’s important to check for errors such as the file not opening (fopen
returning NULL
) or incorrectly formatted input. Misusing fscanf()
can lead to buffer overflows or incorrect data interpretation.
In summary, fscanf()
provides a powerful tool for reading structured data from files in C, making it ideal for applications like configuration readers, data import tools, or file-based databases. Proper use includes always checking if the file was successfully opened and ensuring the format string matches the actual file content.