繁体   English   中英

SEEK_CUR 指向似乎错误的值

[英]SEEK_CUR points to value that seems wrong

这是《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;
}

两个字节的向后查找是正确的。

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

    XYZ
      ^

Z 被读取,位置就在 Z 之后(下一次读取将发出文件结束信号)。

    XYZ
       ^

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

    XYZ
     ^

如果你想阅读下一封信,你根本不需要备份。 如果你想一遍又一遍地阅读同一个字母,你需要在每次阅读后备份一个空格。 因此,要阅读前一个字母,您需要备份两个空格。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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