读书共享 Primer Plus C-part11
Posted 刘传武
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了读书共享 Primer Plus C-part11相关的知识,希望对你有一定的参考价值。
第十四章结构和其他数据形式
关于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=
以上是关于读书共享 Primer Plus C-part11的主要内容,如果未能解决你的问题,请参考以下文章