我只是想知道这段代码为什么你必须在 fseek(fptr, -1, SEEK_END);
结束前的 1 个地方开始阅读,为什么你必须返回 2 个地方fseek(fptr, -2, SEEK_CUR);
#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;
}
最佳答案
假设你在文件中的位置 X,然后你读取一个字符将位置移动到位置 X+1,然后你想转到 X 之前的字符,即位置 X-1。从位置 X+1 到位置 X-1 需要寻求多少?您需要寻找 -2 个职位。
关于c - 不确定 c 中的 fseek 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32606624/