zoukankan      html  css  js  c++  java
  • fread和fwrite和feof读写二进制文件

    #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("参数不够!
    ");
    	}
    	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
    ",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
    ",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
    ",stu.xh, stu.name, stu.age);
    		fread(&stu, sizeof(stu),1,fp1);//必须加
    	}
    	
    	fclose(fp1);
    	fclose(fp2);
    }
    

      

  • 相关阅读:
    [UWP]实现Picker控件
    [UWP]合体姿势不对的HeaderedContentControl
    [UWP]新控件ColorPicker
    [UWP]使用Acrylic(亚克力)
    [UWP]使用Reveal
    [工具]我怎么使用思维导图
    python数据分析师面试题选
    R %operator% 含义
    R中将list类型数据转换成data.frame型
    用R在字符串中提取匹配的部分
  • 原文地址:https://www.cnblogs.com/wanglijun/p/8620711.html
Copyright © 2011-2022 走看看