мне было просто интересно с этим кодом, почему вы должны начать читать на 1-е место до конца в fseek(fptr, -1, SEEK_END);
и почему вы должны вернуться 2 места вместо 1 в fseek(fptr, -2, SEEK_CUR);
неуверены FSEEK синтаксиса с
#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;
}
ohhh поэтому, когда вы читаете, вы перемещаете курсор по тому, что вы читаете. Спасибо за это! – Daniel
И если вы все еще задаетесь вопросом о первом вопросе: 'fseek (fptr, 0, SEEK_END)' будет помещать указатель _just beyond_ в последний символ файла, поэтому вам нужно 'fseek (fptr, -1, SEEK_END)' чтобы быть в правильном положении, чтобы прочитать последний символ. – TripeHound
Если вы выполняете много вызовов 'fseek()' вместе с 'fgetc()' и/или небольшими 'fread()' вызовами, вам, вероятно, лучше отключить буферизацию с помощью 'setbuf()' или 'setvbuf() '; или используя 'open()', 'lseek()' и 'read()' или просто 'pread()'. «По умолчанию IOFILE *» по умолчанию буферизуется, а размер буфера обычно составляет примерно 8 КБ. Но 'fseek()' приведет к недействительности буфера, что приведет к тому, что ваш следующий маленький 'fread()' или 'fgetc()' (однобайтовый текст) будет с большой вероятностью читать весь 8 КБ - снова и снова. –