c-SEEK_CUR指向的值似乎是错误的



这是《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
^

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

最新更新