fscanf

Input-Output Functions

Reads formatted input from a stream.

int fscanf( FILE *file_pointer, const char *format string [, args]);

file_pointer A pointer to a file.
string One or more formatting characters.
args One or more optional print arguments.

For fscanf details, refer to your C language documentation.

Return Values

The number of items successfully read. This count does not include any ignored fields. If EOF is returned, an error has occurred before the first assignment could be performed.

Example

This example creates a log file and writes the following to it:

  • the string "Vuser"

  • the integer "Vuser ID"

  • the time, as returned by the time function.

Using fscanf, it then reads these values back into separate variables.

    #include <stdio.h>
    #include <time.h>
    #ifdef unix
        char * filename = "/tmp/logfile.txt";
    #else
        char * filename = "c:\\logfile.txt";
    #endif
    FILE* file, thetime;
    int id, id2;
    time_t t;
    char s[32];
    // Create a new file 
    if ((file = fopen(filename, "w" )) == NULL) {
        lr_output_message ("Unable to create %s", filename);
        return -1;
    }
    // Write the Vuser ID and time
    lr_whoami (&id, NULL, NULL);
    fprintf(file, "Vuser %d %ld", id, time(&t));
    // Now read what we've just written. Rewind to start of file 
    rewind(file);
    fscanf(file, "%s", &s);
    fscanf(file, "%d", &id2);
    fscanf(file, "%ld", &thetime);
    lr_output_message ("%s %d %ld", s, id2, thetime);
    fclose(file);
Example: Output: 
Vuser -1 1020675497