SEEK_CUR 指向似乎错误的值
SEEK_CUR points to value that seems wrong
这是 "C programming Absolute beginners guide" 书中的一个程序。它使用 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
^
如果你想读下一封信,你根本不用后退。如果您想一遍又一遍地阅读同一封信,则需要在每次阅读后备份一个 space。因此,要阅读上一封信,您需要备份两个 spaces。
这是 "C programming Absolute beginners guide" 书中的一个程序。它使用 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
^
如果你想读下一封信,你根本不用后退。如果您想一遍又一遍地阅读同一封信,则需要在每次阅读后备份一个 space。因此,要阅读上一封信,您需要备份两个 spaces。