简体   繁体   中英

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;
}

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
     ^

If you want to read the next letter, you don't back up at all. If you want to read the same letter over and over again, you would need to back up one space after each read. To read the previous letter, therefore, you would need to back up two spaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM