How to write and read struct from file in C

1 Answer

0 votes
#include <stdio.h>

typedef struct Point {
    int x, y;
} Point;
 
int main(void) {
	 Point p = {
        .x = 89731,
        .y = 26
    };
     
    FILE *out = fopen("data.bin", "wb");
    if (out == NULL) {
        return 1;
    }
     
    size_t total_written = fwrite(&p, sizeof(Point), 1, out);
    fclose(out);
     
    if (total_written == 0) {
        return 1;
    }
	
	Point p1;
    
    FILE* in = fopen("data.bin", "rb");
	
    if (in == NULL) {
        return 1;
    }
    
    size_t total_read = fread(&p1, sizeof(Point), 1, in);
    fclose(in);

    if (total_read == 0) {
        return 2;
    }
    
    printf("%d, %d\n", p1.x, p1.y);
 
    return 0;
}

 

 
 
/*
run:
 
89731, 26
   
*/

 



answered Dec 30, 2020 by avibootz

Related questions

1 answer 137 views
1 answer 258 views
2 answers 270 views
270 views asked Dec 30, 2020 by avibootz
1 answer 204 views
1 answer 263 views
1 answer 160 views
...