size_t fwrite (const void *buffer, size_t size, size_t count, FILE *stream); buffer-points to the storage location where the data is to be written size-the maximum number of bytes count-write target, that is, how many size data is written stream-the file structure pointer
Example:
Define a struct body
struct Student{int NID;//study number char chname[20]; Name float fscores[2]; 2 Results of the course};
void Main () {int i=0; FILE *FP; struct student tstu[3]={{1, "JX", 99,100}, {2, "SLKD", "3", "sldd", 100, 78}};//struct array if (fp = fopen ("f:\\ 1.txt "," WB ")) = = 0) { printf (" Func fopen () err!\n "); return; } for (i=0; i<3; i++) { if (fwrite (&tstu[i],sizeof (struct student), 1,FP)!=1) { printf ("Func Fwrite () Err!\n "); return; } } Fclose (FP); }
The above code writes the binary data in the F drive
The following is read with the Fread () function:
size_t fread (void *buffer, size_t size, size_t count, FILE *stream), buffer-points to where the data is stored size-target bytes count-The maximum number of read targets, That is, how many size size data are read stream-file structure pointer
void Main () {file *pread;struct student tstu[4];//struct-body array struct student *ptstu = null;int ncount = 0;//Open file for reading Pread=fopen (" F:/1.txt "," RB "); if (NULL = = PRead) {printf (" func fopen () Err! \ n "); return;} Read Ptstu = Tstu;ncount = Fread (ptstu,sizeof (struct student), 1,pread), while (ncount>0) {printf ("%d%s%.1f%.1f\n ", Ptstu->nid,ptstu->chname,ptstu->fscores[0],ptstu->fscores[1]);p Tstu++;ncount = Fread (ptStu,sizeof ( struct student), 1,pread);} Fclose (PRead);}
The results are as follows:
Fread () and fwrite () functions for file operations