与 C 中的 fseek() 混淆

问题描述 投票:0回答:1

我是 C 编程语言新手。我正在学习文件 I/O,并且对 fseek 函数感到困惑。这是我的代码

#include <stdio.h>
#include <stdlib.h>

struct threeNumbers 
{
    int n1, n2, n3;
}

int main ()
{
    int n;
    struct threeNumbers number;
    FILE *filePointer;

    if ((filePointer = fopen("\\some_folder\program.bin", "rb")) == NULL)
    {
        printf("error! opening file");
        /* if pointer is null, the program will exit */
        exit(1);
    }

    /* moves the cursor at the end of the file*/
    fseek(filePointer, -sizeof(struct threeNumbers), SEEK_END);

    for(n = 1; n < 5; ++n) 
    {
        fread(&number, sizeof(struct threeNumbers), 1, filePointer);
        printf ("n1: %d \t n2: %d \t n3: %d",number.n1, number.n2, number.n3);
        fseek(filePointer, sizeof(struct threeNumbers) * -2, SEEK_CUR);
    }

    fclose(filePointer);
    return 0;
}

我知道这个程序将开始以相反的顺序(最后到第一个)从文件program.bin中读取记录并打印它。 我的困惑是我知道

fseek(filePointer,-sizeof(struct threeNumbers),SEEK_END);
会将光标移动到二进制文件的末尾。
fseek(filePointer,-2*sizeof(struct threeNumbers),SEEK_CUR);
有什么作用?我认为它会移动到当前位置,但是在这个程序中光标移动到当前位置有什么意义呢?另外为什么它是 -2 而不是只是
-sizeof(struct threeNumbers)

c
1个回答
1
投票

不管实际的代码,这就是

fseek()
所做的:

       The  fseek()  function  sets the file position indicator for the stream
       pointed to by stream.  The new position, measured in bytes, is obtained
       by  adding offset bytes to the position specified by whence.  If whence
       is set to SEEK_SET, SEEK_CUR, or SEEK_END, the offset  is  relative  to
       the  start of the file, the current position indicator, or end-of-file,
       respectively.  A successful call to the  fseek()  function  clears  the
       end-of-file  indicator  for  the  stream  and undoes any effects of the
       ungetc(3) function on the same stream.

fseek(filePointer,-sizeof(struct threeNumbers),SEEK_END)
not“将光标移动到二进制文件末尾”;它会将其移动到文件末尾之前
sizeof(struct threeNumbers)

© www.soinside.com 2019 - 2024. All rights reserved.