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,855 questions

51,776 answers

573 users

How to read struct from binary file in C

2 Answers

0 votes
#include <stdio.h>

typedef struct Point {
    int x, y;
} Point;
 
int main(void) {
	Point p;
    
    FILE* in = fopen("data.bin", "rb");
	
    if (in == NULL) {
        return 1;
    }
    
    size_t total_read = fread(&p, sizeof(Point), 1, in);
    fclose(in);
    if (total_read == 0) {
        return 2;
    }
    
    printf("%d, %d\n", p.x, p.y);
 
    return 0;
}

 

 
 
/*
run:
 
89731, 26
   
*/

 



answered Dec 30, 2020 by avibootz
0 votes
// A c program that read a struct from binary file 
 
#include <stdio.h>
  
struct Numbers {
   int n1, n2;
};
 
int main(void)
{
    struct Numbers N;
    FILE *fp;
 
    if ((fp = fopen("d:\\data.bin", "rb")) == NULL) {
        printf("Error open file");
        return 1;
    }
 
    for (int i = 1; i <= 3; i++) {
        fread(&N, sizeof(struct Numbers), 1, fp); 
        printf("n1 = %d n2 = %d\n", N.n1, N.n2);
    }
     
    fclose(fp); 
  
    return 0;
}
 
 
   
/*
run:
 
n1 = 1 n2 = 2
n1 = 2 n2 = 3
n1 = 3 n2 = 4
 
*/

 



answered Apr 20, 2024 by avibootz

Related questions

1 answer 216 views
1 answer 181 views
1 answer 151 views
151 views asked Dec 30, 2020 by avibootz
1 answer 130 views
1 answer 112 views
1 answer 128 views
...