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)
?
You need to sign in to view this answers
Leave feedback about this