Reading a Text File

While fscanf can be used for reading a text file, it is more common to read the file one line at a time using the command fgets. Each line can be processed as it is read. The format for fgets is as follows:

    fgets(<buffer to put the data in>, <maximum size buffer can hold>, <file pointer>);
The buffer is a large character string where the text read from the file can be stored.

The command fgets is used in conjunction with the command feof, which 0 when the end of the file has not be reached. The format for this command is:

    feof(<file pointer>);
Data has been read from a file until feof does not return 0. (eof stands for end of file)

Each line read from the file can be processed using the command sscanf (string scanf). sscanf is the same as scanf except it works on a string, rather than the input stream. The format for sscanf is:

    sscanf(%lt;buffer to scan>, <format string>, arg1, arg2, ... argN);
where arg1 to argN are the variables where the data extracted from the buffer should be shown.

That is a lot of information! Lets bring all the above concepts together with a simple program. Consider a file called marks.txt that is stored in c: (c:\marks.txt). Marks.txt has the following data:

Monica 78.3 67.2
Jane 45.2 69.6
Jessica 98.4 41.2
Sue 76.8 74.2
Wincate 89.8 84.2

Notice that each line has the same format, a name followed by two grades. The following program reads the file and echoes the results to the screen. To test this program, create a file in C: called marks.txt with the above data.

#include <stdio.h>

int main(int argc, char* argv[])
{
    FILE * fp;  /*creates a FILE pointer named fp*/
    char buffer[1001];
    char name[64];
    float mark1, mark2, avg;

    fp = fopen("c:/marks.txt", "r");
    if(!fp)
    {
        printf("Could not open file.  Giving up.\n");
        return 0;
    }

    fgets(buffer, 1000, fp);

    while(feof(fp) == 0)
    { /*read some data, lets process it.*/
        /*extract individual values from the buffer*/
        sscanf(buffer, "%s%f%f", name, &mark1, &mark2);

        /*echo the data to the screen*/	
        printf("Read data:\n%s %f %f\n", name, mark1, mark2);

        /*calculate the average of the read data*/
        avg = (mark1+mark2)/2.0;
        /*display the average*/
        printf("The average is %f\n", avg);
        printf("%s's average is %4.2f\n",name, avg);
            /*note, the %4.2f says to display four digits, 
                  two of them after the decimal place.*/        

        /*read the next line from the file*/
        fgets(buffer, 1000, fp);
    }

    printf("All the data from the file has been read!\n");

    fclose(fp);

    return 0;
}

next


 home                      table of contents                      about