檔案操作之fread()和fwrite()函數

來源:互聯網
上載者:User

標籤:c語言   檔案操作   

size_t  fwrite( const void *buffer, size_t size, size_t count, FILE *stream );buffer-指向要寫資料的儲存位置size-目標所佔位元組數count-寫目標的最大數量,即寫入多少個size大小的資料stream-檔案結構指標

舉例:

定義一個結構體

struct student{int      nID; //學號char     chName[20];    //姓名float    fScores[2];    //2門課的成績};
 void main() { int i=0; FILE *fp; struct student tStu[3]={{1,"jx",99,100},                         {2, "slkd",89, 90},                         {3, "sldd", 100, 78}};//結構體數組 if((fp = fopen("F:\\1.txt", "wb")) == 0)  {  printf("func fopen() err!\n");  return;  }  for(i=0; i<3; i++)  {  if(fwrite(&tStu[i],sizeof(struct student),1,fp)!=1)  {  printf("func fwrite() err !\n");  return;  }  }    fclose(fp);  }
以上代碼在F盤寫入位元據

下面用fread()函數讀出:

size_t  fread( void *buffer, size_t size, size_t count, FILE *stream );buffer-指向資料的儲存位置size-目標所佔位元組數count-讀取目標的最大數量,即讀取多少個size大小的資料stream-檔案結構指標
void main(){FILE *pRead;struct student tStu[4];//結構體數組struct student *ptStu = NULL;int nCount = 0;//開啟檔案 用於讀取pRead=fopen("F:/1.txt","rb");if(NULL == pRead){printf("func fopen() err ! \n");return;}//一條條的讀取ptStu = tStu;nCount = fread(ptStu,sizeof(struct student),1,pRead);while(nCount>0){printf("%d %s %.1f %.1f\n",ptStu->nID,ptStu->chName,ptStu->fScores[0],ptStu->fScores[1]);ptStu++;nCount = fread(ptStu,sizeof(struct student),1,pRead);}fclose(pRead);}
結果如下:





檔案操作之fread()和fwrite()函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.