Created
May 24, 2021 13:27
-
-
Save harieamjari/4f9211a36246d2e9756f965dde85519c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdint.h> | |
typedef struct student student; | |
struct student { | |
char name[100]; | |
char status; | |
int id; | |
}; | |
int main(){ | |
uint32_t nb_students = 5; | |
student class[5] = { | |
{"Albert", 'S', 1001}, | |
{"Maria", 'A', 1002}, | |
{"John", 'A', 1003}, | |
{"Harie", 'S', 1004}, | |
{"Mana", 'F', 1005} | |
}; | |
FILE *fpout = fopen("file.bin", "wb"); | |
if (fpout==NULL){ | |
perror("file.bin"); | |
return 1; | |
} | |
fwrite("HARI", sizeof(char), 4, fpout); | |
fwrite(&nb_students, sizeof(uint32_t), 1, fpout); | |
fwrite(class, sizeof(struct student), nb_students, fpout); | |
fclose(fpout); | |
FILE *fpin = fopen("file.bin", "rb"); | |
if (fpin==NULL){ | |
perror("file.bin"); | |
return 1; | |
} | |
char HARITag[4] = {0}; | |
fread(HARITag, sizeof(char), 4, fpin); | |
if (strncmp(HARITag, "HARI", 4)){ | |
printf("%s: unrecognized file format\n", "file.bin"); | |
return 1; | |
} | |
/* overwrites nb_students value with what is read */ | |
fread(&nb_students, sizeof(uint32_t), 1, fpin); | |
/* overwrites class values with what is read */ | |
fread(class, sizeof(struct student), nb_students, fpin); | |
fclose(fpin); | |
for (int i = 0; i < nb_students; i++) | |
printf("%s %c %d\n", class[i].name, class[i].status, class[i].id); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment