fread和fwrite函數功能函數
用來讀寫一個數據塊。spa
通常調用形式指針
fread(buffer,size,count,fp);orm
fwrite(buffer,size,count,fp);原型
說明it
(1)buffer:是一個指針,對fread來講,它是讀入數據的存放地址。對fwrite來講,是要輸出數據的地址。io
(2)size:要讀寫的字節數;form
(3)count:要進行讀寫多少個size字節的數據項;stream
(4)fp:文件型指針。file
注意:1 完成次寫操(fwrite())做後必須關閉流(fclose());
2 完成一次讀操做(fread())後,若是沒有關閉流(fclose()),則指針(FILE * fp)自動向後移動前一次讀寫的長度,不關閉流繼續下一次讀操做則接着上次的輸出繼續輸出;
3 fprintf() : 按格式輸入到流,其原型是int fprintf(FILE *stream, const char *format[, argument, ...]);其用法和printf()相同,不過不是寫到控制檯,而是寫到流罷了。注意的是返回值爲這次操做寫入到文件的字節數。如int c = fprintf(fp, "%s %s %d %f", str1,str2, a, b) ;str1:10字節;str2: 10字節;a:2字節;b:8字節,c爲33,由於寫入時不一樣的數據間自動加入一個空格。
文件使用以後必定要關閉,不然將不能正確顯示內容.fwrite:讀入兩個學生信息而後用fwrite存入文件
fread:用fread從文件中讀出學生信息。
fwrite.c
#include <stdio.h>
#define SIZE 2
struct student_type
{
char name[10];
int num;
int age;
char addr[10];
}stud[SIZE];
void save()
{
FILE *fp;
int i;
if((fp=fopen("stu_list","wb"))==NULL)
{
printf("cant open the file");
exit(0);
}
for(i=0;i<SIZE;i++)
{
if(fwrite(&stud[i],sizeof(struct student_type),1,fp)!=1)
printf("file write error\n");
}
fclose(fp);
}
main()
{
int i;
for(i=0;i<SIZE;i++)
{
scanf("%s%d%d%s",&stud[i].name,&stud[i].num,&stud[i].age,&stud[i].addr);
save();
}
for(i=0;i<SIZE;i++)
{
printf("%s,%d,%d",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
}
}
fread.c
#include <stdio.h>
#define SIZE 2
struct student_type
{
char name[10];
int num;
int age;
char addr[10];
}stud[SIZE];
void read()
{
FILE *fp;
int i;
if((fp=fopen("stu_list","rb"))==NULL)
{
printf("cant open the file");
exit(0);
}
for(i=0;i<SIZE;i++)
{
if(fread(&stud[i],sizeof(struct student_type),1,fp)!=1)
printf("file write error\n");
}
fclose(fp);
}
main()
{
int i;
read();
for(i=0;i<SIZE;i++)
{
printf("%s,%d,%d,%s",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
printf("\n");
}
}