Previous Page
Next Page

fscanf

Reads formatted data from an open file

#include <stdio.h>
int fscanf ( FILE * restrict fp , const char * restrict format , ... );

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:1002:, 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" );          // Read and discard rest of line.
}

/* 2. Read the "gecos" field, which may contain nothing, or just the real
 *    name, or comma-separated sub-fields.
 */
results = fscanf( fp, "%256[^:]:", gecos );
if ( results < 1 )
  strcpy( recptr->realname,  "[No real name available]" );
else
  sscanf( gecos, "%128[^,]", recptr->realname ); // Truncate at first comma.

/* 3. Read two more fields before the end of the line. */

results = fscanf( fp, "%128[^:]:%128[^:\n]\n",
                  recptr->home, recptr->shell );
if ( results < 2 )
{
  fprintf( stderr, "Unable to parse line.\n" );
  fscanf( fp, "%*[^\n]\n" );        // Read and discard rest of line.
}
printf( "The user account %s with UID %u belongs to %s.\n",
         recptr->user, recptr->uid, recptr->realname );

For our sample input line, the printf( ) call produces the following output:

The user account tony with UID 1002 belongs to Tony Crawford.

See Also

scanf( ), sscanf( ), vscanf( ), vfscanf( ), and vsscanf( ); wscanf( ), fwscanf( ), swscanf( ), vwscanf( ), vfwscanf( ), and vswscanf( )


Previous Page
Next Page