/*
Read and write a set of data to a file in a binary way
The general method of invocation is:
Fread (BUFFER,SIZE,COUNT,FP);
Fwrite (BUFFER,SIZE,COUNT,FP);
which
Buffer: is an address that, for Fread, is the address of the store where the data read from the file is stored.
For fwrite, the data in the store where this address starts is to be output to the file (above refers to the start address)
Size: Number of bytes to read and write
Count: How many data items to read and write (the length of each data item is size)
Fp:file Type pointer
Input 10 students ' data from the keyboard, then dump them on disk
*/
#include <stdio.h>
#include <stdlib.h>
#define SIZE 3
struct Student_type
{
Char name[10];
int num;
int age;
Char addr[30];
}stu[size];//defines a global struct-body array stu, containing data for 10 students
void Save ()
{
FILE *FP;
int i;
if ((Fp=fopen ("F:\\file_1\\file_5.txt", "WB")) ==null)
{
printf ("Can ' t open file\n");
Exit (0);
Return
}
for (i=0;i<size;i++)
{
if (fwrite (&stu[i],sizeof (struct student_type), 1,FP)!=1)
Fputs ("\ n", FP);
printf ("File Write error!\n");
}
Fclose (FP);
}
void print ()
{
FILE *FP;
int i;
if ((Fp=fopen ("F:\\file_1\\file_5.txt", "RB")) ==null)
{
printf ("Can ' t open file!\n");
Exit (0);
}
for (i=0;i<size;i++)
{
Fread (&stu[i],sizeof (struct student_type), 1,FP);
printf ("%-10s%4d%4d%-25s\n", stu[i].name,stu[i].num,stu[i].age,stu[i].addr);
}
Fclose (FP);
}
int main ()
{
int i;
printf ("Please enter data of students:\n");
for (i=0;i<size;i++)
scanf ("%s%d%d%s", stu[i].name,&stu[i].num,&stu[i].age,stu[i].addr);
Save ();
Print ();
return 0;
}
Read and write a set of data to a file in binary mode