Reading and Writing Values

Writing a value to a file and reading it from a file work exactly like reading and writing values from standard input and output. File-based versions of standard I/O functions are used, so the process should be familiar to you. Still, there’s an interesting catch.

The key to reading values is knowing the file’s format. You could use the example from last week’s Lesson to scan the file input buffer for values, but the operation works best when you know a specific value lurks within a file and how that value is formatted, as raw data or as text.

In the following code, the value 1088 is written to the file highscore.dat. The fprintf() function writes the value by using a format string — familiar stuff. The only addition is the file’s FILE variable handle, which is the function’s first argument. To read back the value, the fscanf() function is used. Like fprintf(), its argument list also sports a file handle variable.

#include <stdio.h>

int main()
{
    const char filename[] = "highscore.dat";
    int score = 1088;
    FILE *hs;

    /* create the file and write the value */
    printf("Writing high score: %d\n",score);
    hs = fopen(filename,"w");
    if( hs == NULL)
    {
        fprintf(stderr,"Error writing to %s\n",filename);
        return(1);
    }
    fprintf(hs,"%d",score);
    fclose(hs);

    /* open the file and read the value */
    hs = fopen(filename,"r");
    if( hs == NULL)
    {
        fprintf(stderr,"Error reading from  %s\n",filename);
        return(1);
    }
    fscanf(hs,"%d",&score);
    printf("Reading high score: %d\n",score);
    fclose(hs);

    return(0);
}

Aside from all the checks to ensure files are opened properly, this code isn’t that complex: A file is opened, the fprintf() statement at Line 17 sends the value of variable score out to the file. The file is closed.

After the file is opened for reading at Line 21, the fscanf() function reads the file’s text for an integer value, storing the result in the score variable.

Here’s a sample run:

Writing high score: 1088
Reading high score: 1088

The value written to and read from the file is stored as text — just as it would be had this program read from standard input and written to standard output. On my computer, the contents of the file highscore.dat are the characters 1, 0, 8, and 8. Because a newline wasn’t written to the file, it’s not stored.

If you modify the code to write a real number to the file, it’s also stored as plain text.

To write raw data to a file and then read that raw data back into a variable, you must use different file I/O statements. I cover this topic in next week’s Lesson.

Leave a Reply