Search code examples
cfseek

SEEK_CUR points to value that seems wrong


This is a program from the book "C programming Absolute beginners guide". It uses fseek and SEEK_CUR. When it comes to printing to the screen, I can understand why it prints'Z'correctly, but I cannot understand why it prints 'Y'correctly. For the fseek within the loop, the code is written as fseek(fptr, -2, SEEK_CUR), so surely this must mean that it moves down two bytes from 'Z' and should print 'X' instead of 'Y'? Thanks for your help in advance.

    // File Chapter29ex1.c

/* This program opens file named letter.txt and prints A through Z into the file.
It then loops backward through the file printing each of the letters from Z to A. */

#include <stdio.h>
#include <stdlib.h>
FILE * fptr;

main()
{
    char letter;
    int i;

    fptr = fopen("C:\\users\\steph\\Documents\\letter.txt","w+");

    if(fptr == 0)
    {
        printf("There is an error opening the file.\n");
        exit (1);
    }

    for(letter = 'A'; letter <= 'Z'; letter++)
    {
        fputc(letter,fptr);
    }

    puts("Just wrote the letters A through Z");


    //Now reads the file backwards

    fseek(fptr, -1, SEEK_END);  //minus 1 byte from the end
    printf("Here is the file backwards:\n");
    for(i= 26; i> 0; i--)
    {
        letter = fgetc(fptr);
        //Reads a letter, then backs up 2
        fseek(fptr, -2, SEEK_CUR);
        printf("The next letter is %c.\n", letter);
    }

    fclose(fptr);

    return 0;
}

Solution

  • The backwards seek of two bytes is correct.

    Suppose that the current position of the file is at (just before) Z. The arrow points to the next character that will be read.

        XYZ
          ^
    

    Z is read, and the position is just after Z (the next read will signal end-of-file).

        XYZ
           ^
    

    Seeking backwards two bytes will put the position of the file just before Y, meaning that the next read will obtain Y as expected:

        XYZ
         ^