1. 程式人生 > >讀書共享 Primer Plus C-part11

讀書共享 Primer Plus C-part11

clu ++ div string rime prime processor type 1.0

第十四章結構和其他數據形式

關於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.out

liuchuanwu0
linux:/home/lcw/code # cat book.list
p?Kliuchuanwu0¢ÿÿÿÿ¢p¢¢D.ι
¶?¸@

liu chuan wu 0?h¢.N=

讀書共享 Primer Plus C-part11