1. 程式人生 > >fread和fwrite和feof讀寫二進制文件

fread和fwrite和feof讀寫二進制文件

name std 文本文件 數據 () write void tdi post

#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讀寫二進制文件