- #include <stdio.h>
- #define SIZE 10
- struct student
- {
- Char name[10];
- int num;
- int age;
- Char addr[15];
- }stu[size];
- Save Data (fwrite)
- void Save ()
- {
- FILE *FP;
- fp = fopen ("Stu.dat", "WB");
- if (fp==null)
- {
- printf ("File can not open!\n");
- Return
- }
- for (int i=0;i<size;i++)
- {
- if (fwrite (&stu[i],sizeof (struct student), 1,FP)!=1)
- {
- printf ("File Write error!\n");
- }
- }
- Fclose (FP);
- }
- Read Data (fread)
- void Load ()
- {
- FILE *FP;
- fp = fopen ("Stu.dat", "RB");
- if (fp==null)
- {
- printf ("File can not open!\n");
- Return
- }
- for (int i=0;i<size;i++)
- {
- if (fread (&stu[i],sizeof (struct student), 1,FP)!=1)
- {
- if (feof (FP))
- {
- Fclose (FP);
- Return
- }
- printf ("file read error!\n");
- }
- printf ("%-10s%4d%4d%-15s\n", stu[i].name,stu[i].num,stu[i].age,stu[i].addr);
- }
- Fclose (FP);
- }
- int main ()
- {
- printf ("Please enter data of students:\n");
- for (int i=0;i<size;i++)
- {
- scanf ("%s%d%d%s", stu[i].name,&stu[i].num,&stu[i].age,stu[i].addr);
- }
- Save ();
- Load ();
- return 0;
- }
C: Read and write a set of data to a file in binary mode (fread, fwrite)