为什么在向后打印文本文件的程序中调用 fseek 时偏移量为 -2 而不是偏移量 -1?
Why should fseek be called with offset of -2 instead an offset of -1 in the program that prints the text file backwards?
以下 C 程序反向打印文本文件:
#include <stdio.h>
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2
int main(int argc, char **argv)
{
FILE *fp = f
open(argv[1], "r");
fseek(fp, -1L, SEEK_END);
while (ftell(fp))
{
putchar(fgetc(fp));
fseek(fp, -2L, SEEK_CUR);
}
putchar(fgetc(fp));
由于程序应该向后打印文本文件,所以应该从末尾读取每个字符,不跳过任何字符。如果是这样,我认为 while 循环中的调用应该是
fseek(fp, -1L, SEEK_CUR);
为什么偏移量是-2而不是-1?
提前致谢!
当您调用 fgetc 时,偏移量比您期望的提前 1 个字符,因此您需要向后移动 2 个字符才能获得您期望获得的字符。否则你会一直得到相同的字符。
以下 C 程序反向打印文本文件:
#include <stdio.h>
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2
int main(int argc, char **argv)
{
FILE *fp = f
open(argv[1], "r");
fseek(fp, -1L, SEEK_END);
while (ftell(fp))
{
putchar(fgetc(fp));
fseek(fp, -2L, SEEK_CUR);
}
putchar(fgetc(fp));
由于程序应该向后打印文本文件,所以应该从末尾读取每个字符,不跳过任何字符。如果是这样,我认为 while 循环中的调用应该是
fseek(fp, -1L, SEEK_CUR);
为什么偏移量是-2而不是-1?
提前致谢!
当您调用 fgetc 时,偏移量比您期望的提前 1 个字符,因此您需要向后移动 2 个字符才能获得您期望获得的字符。否则你会一直得到相同的字符。