简体   繁体   English

SEEK_CUR 指向似乎错误的值

[英]SEEK_CUR points to value that seems wrong

This is a program from the book "C programming Absolute beginners guide".这是《C 编程绝对初学者指南》一书中的程序。 It uses fseek and SEEK_CUR.它使用 fseek 和 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.当谈到打印到屏幕上时,我可以理解为什么它会正确打印“Z”,但我无法理解为什么它会正确打印“Y”。 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'?对于循环中的 fseek,代码写为 fseek(fptr, -2, SEEK_CUR),所以这肯定意味着它从“Z”向下移动两个字节,并且应该打印“X”而不是“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.假设文件的当前位置在(就在之前)Z。箭头指向将要读取的下一个字符。

    XYZ
      ^

Z is read, and the position is just after Z (the next read will signal end-of-file). Z 被读取,位置就在 Z 之后(下一次读取将发出文件结束信号)。

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

    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.因此,要阅读前一个字母,您需要备份两个空格。

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

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