Fread () and fwrite () functions for file operations

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.