標籤: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()函數