首页 > 其他 > 详细

fread和fwrite和feof读写二进制文件

时间:2018-03-22 00:12:46      阅读:240      评论:0      收藏:0      [点我收藏+]
#include <stdio.h>
#include <stdlib.h>

void text_to_bin(char *argv[]);
void bin_to_text();

typedef struct
{
	int xh;
	char name[20];
	int age;
}Student;
int main(int a,char *argv[]){
	
	if(a!=4){
		printf("参数不够!\n");
	}
	text_to_bin(argv);
	bin_to_text(argv);

	return 0;

}
void text_to_bin(char *argv[]){
	Student stu;
	FILE *fp1, *fp2;
	fp1 = fopen(argv[1],"r");
	if(fp1==NULL){
	     printf("source file open error");
	     exit(1);
	}
	fp2 = fopen(argv[2],"wb");//write b bytes二进制文件 要写入的二进制文件
	if(fp2==NULL){
	     printf("bytes file open error");
		exit(1);	
	}
	while(fscanf(fp1,"%d %s %d", &stu.xh, stu.name, &stu.age)!=EOF){
		//printf("%s\n",stu.name);
		fwrite(&stu, sizeof(stu), 1, fp2);//写入二进制文件stu是指向数据块的二进制结构体变量; 每次写入1个结构体变量
		
	}
	fclose(fp1);
	fclose(fp2);
}
void bin_to_text(char *argv[]){
	Student stu;
	FILE *fp1, *fp2;
	fp1 = fopen(argv[2],"rb");//只读方式读取二进制文件
	if(fp1==NULL){
	     printf("source file open error");
	     exit(1);
	}
	fp2 = fopen(argv[3],"w");//写入文本文件
	if(fp2==NULL){
	     printf("bytes file open error");
		exit(1);	
	}
	//必须>0 循环
/* 	while(fread(&stu,sizeof(stu), 1, fp1)){
		fprintf(fp2, "%d %s %d\n",stu.xh, stu.name, stu.age);
	} */
	
	size_t size = fread(&stu, sizeof(stu),1,fp1);
	if(size==0) return;
	//feof只能用在二进制文件
	while(!feof(fp1)){
		fprintf(fp2, "%d %s %d\n",stu.xh, stu.name, stu.age);
		fread(&stu, sizeof(stu),1,fp1);//必须加
	}
	
	fclose(fp1);
	fclose(fp2);
}

  

fread和fwrite和feof读写二进制文件

原文:https://www.cnblogs.com/wanglijun/p/8620711.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!