How to count the number of structs in a binary file in C

1 Answer

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

#define SIZE 3

struct user {
    char name[16];
    int age;
} vip[SIZE] = {
              {"dan", 43},
              {"ben", 51},
              {"tom", 62}
};


int main()
{
    char filename[16] = "d:\\data.bin";

    // write
    FILE *fp = fopen(filename, "wb");
    if (!fp) {
        printf("Unable to open file");
        return 1;
    }

    for (int i = 0; i < SIZE; i++) {
        fwrite(&vip[i], sizeof(struct user), 1, fp);
    }

    fseek(fp, 0, SEEK_END);
    long file_size = ftell(fp);
    long struct_size = sizeof(struct user);

    printf("file size = %ld\n", file_size);
    printf("struct size = %ld\n", struct_size);
    
    long total_structs = file_size / struct_size;

    printf("total structs = %ld\n", total_structs);

    fclose(fp);


    return 0;
}




/*
run:

file size = 60
struct size = 20
total structs = 3

*/

 



answered Jun 20, 2024 by avibootz

Related questions

1 answer 167 views
2 answers 229 views
2 answers 211 views
2 answers 466 views
466 views asked Oct 18, 2014 by avibootz
1 answer 265 views
265 views asked Oct 17, 2014 by avibootz
1 answer 200 views
2 answers 207 views
...