fscanf() — Read Formatted Data
Format
#include <stdio.h>
int fscanf (FILE *stream, const char *format-string, argument-list);
Language Level
ANSI
Threadsafe
Yes
Locale Sensitive
The behavior of this function might be affected by the LC_CTYPE and LC_NUMERIC categories of the current locale. The behavior might also be affected by the LC_UNI_CTYPE category of the current locale if LOCALETYPE(*LOCALEUCS2) or LOCALETYPE(*LOCALEUTF) is specified on the compilation command. For more information, see Understanding CCSIDs and Locales.
Description
The fscanf()
function
reads data from the current position of the specified stream into
the locations that are given by the entries in argument-list,
if any. Each entry in argument-list must
be a pointer to a variable with a type that corresponds to a type
specifier in format-string.
The format-string controls the
interpretation of the input fields and has the same form and function
as the format-string argument for the scanf()
function.
Return Value
The fscanf()
function
returns the number of fields that it successfully converted and assigned.
The return value does not include fields that the fscanf()
function
read but did not assign.
The return value is EOF if an input failure occurs before any conversion, or the number of input items assigned if successful.
Example
#include <stdio.h>
#define MAX_LEN 80
int main(void)
{
FILE *stream;
long l;
float fp;
char s[MAX_LEN + 1];
char c;
stream = fopen("mylib/myfile", "r");
/* Put in various data. */
fscanf(stream, "%s", &s [0]);
fscanf(stream, "%ld", &l);
fscanf(stream, "%c", &c);
fscanf(stream, "%f", &fp);
printf("string = %s\n", s);
printf("long double = %ld\n", l);
printf("char = %c\n", c);
printf("float = %f\n", fp);
}
/*************** If myfile contains ************************
**************** abcdefghijklmnopqrstuvwxyz 343.2 ***********
********************** expected output is: *********************
string = abcdefghijklmnopqrstuvwxyz
long double = 343
char = .
float = 2.000000
*/