Read and write a set of data to a file in binary mode

Source: Internet
Author: User
Tags fread


/*
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

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.