【发布时间】:2015-09-16 10:54:42
【问题描述】:
我只是想知道这段代码为什么你必须在 fseek(fptr, -1, SEEK_END); 结束前的 1 个位置开始阅读,以及为什么你必须返回 2 个位置而不是 fseek(fptr, -2, SEEK_CUR); 中的 1 个位置
#include <stdio.h>
#include <stdlib.h>
FILE * fptr;
int main()
{
char letter;
int i;
fptr = fopen("/Users/Dan/Documents/Coding/alpbkw/alphabet.txt", "w+");
if (fptr == 0)
{
printf("there was an error opening the file");
exit(1);
}
for (letter = 'A'; letter <= 'Z'; letter++) //knows how to count up the alphabet
{
fputc(letter,fptr); //note syntax. fputc puts characters in a file
}
puts("characters have been written in the file");
fseek(fptr, -1, SEEK_END); //looks in fptr, starts from 1 byte before the end. the -1 is the offset. this statement shows where it starts, not how it cycles. i think end of file doesnt actually have a letter printed on it, its a placeholder or something
printf("here is the file backwards\n");
for (i=26;i>0;i--) //starting from the last and counting backwards. goes through 26 times as expects 26 letters
{
letter = fgetc(fptr); //gets the letter it is currently on and reads it
fseek(fptr, -2, SEEK_CUR); //backs up 2 places, if back up twice you will only print z's.
printf("the next letter is %c.\n", letter);
}
fclose(fptr);
return 0;
}
【问题讨论】: