Unlocking the Power of fscanf(): A Deep Dive into File Stream Reading
The Anatomy of fscanf()
The fscanf() function is defined in the <cstdio>
header file and takes two primary parameters: stream
and format
. The stream
parameter specifies the input file stream to read from, while the format
parameter is a pointer to a null-terminated character string that defines how to read the input.
Cracking the Code: Understanding Format Specifiers
The format string is composed of three main parts: non-whitespace characters, whitespace characters, and conversion specifications.
- Non-whitespace characters match identical characters from the input stream.
- Whitespace characters are treated as single spaces.
- Conversion specifications follow a specific format:
initial % character optional * assignment-suppressing character optional positive integer specifying maximum field width optional length modifier specifying the size of the receiving argument conversion format specifier
Decoding Format Specifiers
Format specifiers are the backbone of fscanf(). They determine what type of data to extract from the input stream and how to store it.
- % matches the literal % character
- c matches a single character or multiple characters
- s matches consecutive non-whitespace characters
- [set] matches a non-empty sequence of characters from a given set
- d matches a decimal integer
- i matches an integer
- o matches an unsigned octal integer
- X or x matches an unsigned hexadecimal integer
- u matches an unsigned decimal integer
- A or a, E or e, F or f, G or g match a floating-point number
- n returns the number of characters read so far
- p matches an implementation-defined character sequence defining a pointer
Return Values and Error Handling
The fscanf() function returns the number of receiving arguments successfully assigned. If a matching failure occurs before the first receiving argument was assigned, it returns zero. If input failure occurs before the first receiving argument was assigned, it returns EOF
.
Putting it all Together: An Example
Let’s see how fscanf() works in practice.
int main() {
FILE *fp;
int id;
char name[20];
float salary;
fp = fopen("employee.txt", "r");
fscanf(fp, "%d %s %f", &id, name, &salary);
printf("ID: %d, Name: %s, Salary: %f\n", id, name, salary);
fclose(fp);
return 0;
}
In this example, fscanf() reads data from an input file stream and stores it in variables id
, name
, and salary
. The format string %d %s %f
specifies the format of the input data, and the function returns the number of receiving arguments successfully assigned.