第十四章结构和其他数据形式
关于fread以及fwrite
- fread(char* buff,int size,int count,FILE* fp)
- fwrite(char* buff,int size,int count,FILE* fp)
#include<stdio.h>
#include<string.h>
typedef struct book_s
{
int count;
char name[100];
char author[100];
float price;
}Book;
int main()
{
Book books[3] ;
strcpy(books[0].name,"liuchuanwu0" );
strcpy(books[0].author,"liu chuan wu 0");
books[0].price = 1.00;
strcpy(books[1].name,"liuchuanwu1" );
strcpy(books[1].author,"liu chuan wu 1");
books[1].price = 1.00;
strcpy(books[2].name,"liuchuanwu2" );
strcpy(books[2].author,"liu chuan wu 2");
books[2].price = 1.02;
FILE * fp =fopen("./book.list","a+");
int index ;
for(index=0;index<3;index++)
{
fwrite(&books[index],sizeof(Book),1,fp);
}
memset(&books[2],0,sizeof(Book));
printf("%s \n",books[2].name);
rewind(fp) ;
fread(&books[2],sizeof(Book),1,fp);
printf("%s \n",books[2].name);
}
结果如下:–结构体可以正常的转存入文件,且vim查看存在乱码,但是可以正常的读写
linux:/home/lcw/code # ./a.outliuchuanwu0
linux:/home/lcw/code # cat book.list
pղKliuchuanwu0¢ÿÿÿÿ¢p¢¢D.ι
¶ҩ¸@
liu chuan wu 0۩h¢.N=