#include #include #include typedef struct { int i1; int i2; char c[20]; } easystruct; typedef struct { int i1; int i2; int ssl; char* c; } hardstruct; int writer() { FILE* f = fopen("wb.bin", "w"); char a = 'w'; int r = fwrite(&a, 1, 1, f); if (r!=1) fprintf(stderr, "writing issue"); char c[20]; for (int i=0; i<20; i++) c[i]='a'+i; r = fwrite(c, 20, sizeof(char), f); if (r!=20*sizeof(char)) fprintf(stderr, "writing issue"); easystruct es[10]; for (int i=0; i<10; i++) { es[i].i1=i+1; es[i].i2=i*i+2; for (int ch=0; ch<19; ch++) es[i].c[ch]='a'+ch; es[i].c[19]='\0'; } fwrite(es, 10, sizeof(easystruct), f); hardstruct hs[10]; for (int i=0; i<10; i++) { hs[i].i1=i+1; hs[i].i2=i*i+2; hs[i].c = malloc(21*sizeof(char)); for (int ch=0; ch<(8+i); ch++) hs[i].c[ch]='B'+ch; hs[i].ssl = 9+i; hs[i].c[8+i]='\0'; } // fwrite(es, 10, sizeof(hardstruct), f); // does not work because of pointer //you have to wriet out the structure parts individually for (int i=0; i<10; i++) { fwrite(&hs[i].i1, sizeof(int),1, f); fwrite(&hs[i].i2, sizeof(int),1, f); // for the malloc'd string, need to write the length of the string // then the string -- in both cases leaving room for the null term fwrite(&hs[i].ssl, sizeof(int), 1, f); fwrite(hs[i].c, sizeof(char), hs[i].ssl, f); } fclose(f); } void reader() { FILE* f = fopen("wb.bin", "r"); char a; int r = fread(&a, 1, 1, f); if (r!=1) fprintf(stderr, "reading issue"); printf("%d\n", a); char c[20]; r = fread(c, 20, sizeof(char), f); if (r!=20*sizeof(char)) fprintf(stderr, "reading issue"); for (int i=0; i<20; i++) printf("%c", c[i]); printf("\n"); easystruct es[10]; r = fread(es, sizeof(easystruct), 10, f); if (r!=(10*sizeof(easystruct))) fprintf(stderr, "Reading issue %d %d\n", 10*sizeof(easystruct), r); for (int i=0; i<10; i++) { printf("ES %d: %d %d %s\n", i, es[i].i1, es[i].i2, es[i].c); } hardstruct hs[10]; for (int i=0; i<10; i++) { fread(&hs[i].i1, sizeof(hs[i].i1),1, f); fread(&hs[i].i2, sizeof(hs[i].i2),1, f); fread(&hs[i].ssl, sizeof(hs[i].ssl),1, f); hs[i].c = malloc(hs[i].ssl*sizeof(char)); fread(hs[i].c, sizeof(char),hs[i].ssl, f); } for (int i=0; i<10; i++) { printf("HS %d: %d %d %s\n", i, hs[i].i1, hs[i].i2, hs[i].c); } fclose(f); } int main() { writer(); reader(); }