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); }
结果如下:
时间: 2024-11-04 15:33:14