不确定c中的fseek语法

时间:2015-09-16 10:54:42

标签: c fseek

我只是想知道这段代码为什么你必须在fseek(fptr, -1, SEEK_END);结束前的1个地方开始阅读,为什么你必须回到fseek(fptr, -2, SEEK_CUR);中的2个地方而不是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;
}

1 个答案:

答案 0 :(得分:2)

假设您在文件中的X位置,然后您读取一个将位置移动到位置X + 1的字符,然后您想要转到位于X-1位置的X之前的字符。你需要从X + 1位置到X-1位置需要多少钱?你需要寻找-2个职位。