[英]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.