Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,853 questions

51,774 answers

573 users

How to write and read an array of structs to and from 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);
    }

    fclose(fp);

    // read
    fp = fopen(filename, "rb");
    if (!fp) {
        printf("Unable to open file");
        return 1;
    }

    struct user u;
    for (int i = 0; i < SIZE; i++) {
        fread(&u, sizeof(struct user), 1, fp);
        printf("%s %d\n", u.name, u.age);
    }

    return 0;
}



/*
run:

dan 43
ben 51
tom 62

*/

 



answered Jun 20, 2024 by avibootz
edited Jun 20, 2024 by avibootz

Related questions

1 answer 136 views
2 answers 193 views
2 answers 221 views
1 answer 202 views
...