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

      

  • 相关阅读:
    27. Remove Element
    26. Remove Duplicates from Sorted Array
    643. Maximum Average Subarray I
    674. Longest Continuous Increasing Subsequence
    1. Two Sum
    217. Contains Duplicate
    448. Find All Numbers Disappeared in an Array
    566. Reshape the Matrix
    628. Maximum Product of Three Numbers
    UVa 1349 Optimal Bus Route Design (最佳完美匹配)
  • 原文地址:https://www.cnblogs.com/wanglijun/p/8620711.html
Copyright © 2011-2022 走看看