More File Access Messing

In last week’s Lesson, I covered the ftell() function, which returns the current file position indicator. That indicator can be manipulated, allowing you to control how a file is read in a non-sequential way.

Normally, file access is sequential: One byte is read after another. As the operating system coughs up those bytes, it uses a file position indicator to keep track of the information read. If you don’t mess with the indicator, the file is read front-to-back. If you mess with the indicator, you can read a file in any order.

One function that drastically messes with the file position indicator is rewind(). It resets the indicator back to zero, effectively starting over. The function takes a single argument, the file pointer variable and it’s declared in the stdio.h header.

The following sample code is based on the example from last week’s Lesson. It uses the file gettysburg.txt, which you can obtain by clicking the filename link.

#include <stdio.h>

int main()
{
    FILE *fh;
    int c;

    /* open the file */
    fh = fopen("gettysburg.txt","r");
    if(fh == NULL)
    {
        perror("Unable to open file\n");
        return(1);
    }

    /* read the file and display */
    while( (c=fgetc(fh)) != EOF)
        putchar(c);
    rewind(fh);
    while( (c=fgetc(fh)) != EOF)
        putchar(c);
    
    /* close the file */
    fclose(fh);

    return(0);
}

The rewind() function resets the file position indicator at Line 22. Lines 23 and 24 are duplicates of the while loop at Lines 20 and 21. So even though the file indicator is at the EOF, the rewind() function resets that pointer and starts over, effectively re-reading the file.

The end result of this sample code is that the same information is read and output twice, but without the need to close and re-open that file.

The rewind() function is absolute. It always resets the file position indicator back to the first byte in a file. If you want to set the indicator to a specific position within the file, you use the fseek() function. I’ll cover that function in next week’s Lesson.

Leave a Reply