Search code examples
cfile-iofseek

understanding usage of fseek


#include<stdio.h>
int main(int argc, char **argv){
    FILE *fp = NULL;
    fp = fopen("D://test.txt","wb");
    if(fp == NULL){
        printf("Error opening file\n");
    }

    typedef struct{
        int a;
        char b;
    }A;

    A x = {12, 'a'}, y = {13, 'b'},z;
    fwrite(&x, sizeof(A), 1, fp);
    fwrite(&y, sizeof(A), 1, fp);

    fseek(fp, sizeof(A), SEEK_SET);

    fread(&z, sizeof(A), 1, fp);
    printf("%d  %c\n", z.a, z.b);
    return 0;
}

I intend to write 2 structures to a file. Then I need to position the file pointer to the beginning of the 2nd structure in the file and then perform fread from there to read the 2nd structure into z. The values are not read into z properly. I am not getting where the problem is.


Solution

  • You opened the file with "wb", write binary. After writing, you are trying to read the same file. Change the mode from "wb" to "wb+":

    //fp = fopen("D://test.txt","wb");
    fp = fopen("D://test.txt","wb+");
    

    to make it work.