Name
fscanf
Synopsis
Reads formatted data from an open file
#include <stdio.h> intfscanf
( FILE * restrictfp
, const char * restrictformat
, ... );
The fscanf()
function is
like scanf()
, except that it
reads input from the file referenced by first argument,
fp
, rather than from stdin
. If fscanf()
reads to the end of the file, it
returns the value EOF
.
Example
The example code reads information about a user from a file, which we will suppose contains a line of colon-separated strings like this:
tony:x:1002:31:Tony Crawford,,:/home/tony:/bin/bash
Here is the code:
struct pwrecord { // Structure to hold contents of passwd fields.
unsigned int uid;
unsigned int gid;
char user[32];
char pw [32];
char realname[128];
char home [128];
char shell [128];
};
/* ... */
FILE *fp;
int results = 0;
struct pwrecord record;
struct pwrecord *recptr = &record;
char gecos[256] = "";
/* ... Open the password file to read ... */
record = (struct pwrecord) { UINT_MAX, UINT_MAX, "", "", "", "", "", "" };
/* 1. Read login name, password, UID and GID. */
results =fscanf
( fp, "%32[^:]:%32[^:]:%u:%u:",
recptr->user, recptr->pw,
&recptr->uid, &recptr->gid );
This function call reads the first part of the input string,
tony:x:1002:31:
, and copies the
two strings "tony"
and "x"
and assigns two unsigned int
values, 1002 and 31, to the
corresponding structure members. The return value is 4. The
remainder of the code is then as follows:
if ( results < 4 )
{
fprintf( stderr, "Unable to parse line.\n" );fscanf
( fp, "%*[^\n]\n" ...
Get C in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.