Abdul Haseeb jabbar
Abdul Haseeb jabbar

Reputation: 39

confusion with fseek() in C

I am new to the C programming language. I am learning file I/O, and am confused with the fseek function. Here is my code

#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;
}

I know that this program will start reading the records from the file program.bin in the reverse order (last to first) and prints it. my confusion is I know that fseek(filePointer,-sizeof(struct threeNumbers),SEEK_END); will move the cursor at the end of the binary file. What does fseek(filePointer,-2*sizeof(struct threeNumbers),SEEK_CUR); do? I think it moves to the current location, but what is the point of the cursor cumming to the current location in this program? Also why is it -2 instead of being just -sizeof(struct threeNumbers)?

Upvotes: 0

Views: 1203

Answers (1)

U. Windl
U. Windl

Reputation: 4325

Disregarding the actual code, this is what fseek() does:

       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) will not "move the cursor at the end of the binary file"; it will move it sizeof(struct threeNumbers) before the end of the file.

Upvotes: 3

Related Questions