Search code examples
cstructbinaryfiles

How to use fread() for each struct field separately when reading binary file?


In my struct I've got the fields

struct records {
    short link; 
    double gate; 
    unsigned char bar;
    int rest; 
    char rink; 
};

And in my main()

int main(int argc, char* argv[]){
    struct records rec;

    if(argc<2){//no paramaters
        //return error
    }

    FILE *fp=fopen(argv[1], "rb");

    if(fp==NULL){//no file
         //return error
    }

    //use fread() for each field in struct separately.   

    fclose(fp);
    return 0;
}

How do you call fread() so that it reads each struct field separately, then prints them out? I know (every similar sort of question and tut online) shows calling fread() by supplying the whole struct, but I don't want to do this, eg. fread(&rec, sizeof(rec), 1, fp). I want to read each field separately with its own fread() call. Any help appreciated, thanks.


Solution

  • fread need two important arguments: a pointer and a length.

    You can easily get both:

    struct records {
        short link; 
        double gate; 
        unsigned char bar;
        int rest; 
        char rink; 
    };
    
    int main(int argc, char* argv[]){
        struct records rec;
    
        // ...
    
        FILE *fp=fopen(argv[1], "rb");
    
        // ...
    
        //use fread() for each field in struct separately.   
    
        while (!feof(fp))
        {
            if (fread(&rec.link, sizeof(rec.link), 1, fp) != 1
               || fread(&rec.gate, sizeof(rec.gate), 1, fp) != 1
               || // etc...
               )
            {
                // error !
            }
            // print the contents of rec, for example...
        }
        // ...
    }