c - 不确定 c 中的 fseek 语法

标签 c fseek

我只是想知道这段代码为什么你必须在 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;
}

最佳答案

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

关于c - 不确定 c 中的 fseek 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32606624/

相关文章:

C 二进制读写文件

c - 如何从 .t​​xt 文件中读取已知数量的未知大小的字符串并将每一行存储在矩阵的一行中(在 C 中)?

c - 使用 malloc/free 时的 __lll_lock_wait_private ()

c - 使用混杂模式

c - qsort 在 c 中按字典顺序对字符串进行排序

c - 让 gdb 与 emacs 24 一起工作

c - ftello/fseeko 与 fgetpos/fsetpos

c - 在 C 中使用 fwrite() 的 fseek() 之后,fread() 不工作

6/2 是否可以返回与 6/a(其中 a=2)不同的结果? (以及这如何影响 .bmp 文件的输出)

c - 编译器中的 Dev C++ 错误