SEEK_CUR指向似乎错误的值

问题描述 投票:0回答:2

这是《 C编程绝对入门指南》一书中的程序。它使用fseek和SEEK_CUR。在屏幕上打印时,我可以理解为什么它正确打印了“ Z”,但是我不明白为什么它正确打印了“ Y”。对于循环内的fseek,代码被编写为fseek(fptr,-2,SEEK_CUR),因此,这肯定意味着它从'Z'下移了两个字节,并且应该打印'X'而不是'Y'吗?感谢您的帮助。

    // 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;
}
c fseek
2个回答
0
投票

两个字节的向后搜索是正确的。

假设文件的当前位置在Z处(正好在Z处。箭头指向将要读取的下一个字符。

    XYZ
      ^

Z被读取,并且位置紧随Z之后(下一次读取将指示文件结束)。

    XYZ
       ^

向后寻找两个字节将把文件的位置放在Y之前,这意味着下一次读取将按预期获得Y:

    XYZ
     ^

0
投票

如果您想阅读下一封信,则完全不会备份。如果要一遍又一遍地读取同一封信,则每次读取后都需要备份一个空格。因此,要阅读上一封信,您需要备份两个空格。

© www.soinside.com 2019 - 2024. All rights reserved.