#include
#include
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);
}