l5-d4 标准IO读写:二进制方式

一、二进制读写概念

文本文件和二进制的区别:

存储的格式不同:文本文件只能存储文本。

计算机内码概念:文本符号在计算机内部的编码(计算机内部只能存储数字0101001....,所以所有符号都要编码)

二进制读写函数格式:

size_t fread(void *ptr, size_t size, size_t n, FILE *fp);

        void *ptr  //读取内容放的位置指针

        size_t size //读取的块大小

        size_t n //读取的个数

        FILE *fp  //读取的文件指针

size_t fwrite(const void *ptr, size_t size, size_t n, FILE *fp);

        void *ptr  //写文件的内容的位置指针

        size_t size //写的块大小

        size_t n //写的个数

        FILE *fp  //要写的文件指针

注意事项:

文件写完后,文件指针指向文件末尾,如果这时候读,读不出来内容。

解决办法:移动指针到文件头;关闭文件,重新打开

二、二进制文件读写代码实现

#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[]){
   FILE *fp;
   char *buff;   
   size_t ret;
   fp=fopen("1.txt","r");
   if(fp==NULL){
      perror("fopen");
      return 0;
   }
   
   buff=(char*)malloc(100);
   if(buff==NULL){
      return 0;

   }

   ret = fread(buff,10,1,fp);
   if(ret==-1){
       perror("fread");
       goto end;
   }
   
   printf("buf=%s\n",buff); 

end:
   free(buff);
   fclose(fp);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct student{
   char name[16];
   int age;
   char sex[8];
};

int main(int argc,char *argv[]){
   FILE *fp;
   size_t ret;
   
   struct student stu2;

   fp=fopen("1.bin","r");
   if(fp==NULL){
      perror("fopen");
      return 0;
   }
   ret = fread(&stu2,sizeof(stu2),1,fp);
   if(ret ==-1){
      perror("fread");
      goto end;
   }

   printf("name=%s,age=%d,sex=%s\n",stu2.name,stu2.age,stu2.sex);
 
end:
   fclose(fp);

}

三、作业

使用标准IO写2个学生的结构体数据到文件。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct student{
	char name[20];
	int age;
	char sex[10];
};

int main(){
	FILE *fp;
	size_t ret;

	struct student stu;
	struct student stu1;
	struct student stu2;

	fp = fopen("1.bin","w");
	if (fp == NULL){
		perror("fopen");
		return 0;
	}
	strcpy(stu1.name,"张三");
	stu1.age = 16;
	strcpy(stu1.sex,"男");
	strcpy(stu2.name,"李四");
	stu2.age = 15;
	strcpy(stu2.sex,"女");

	ret = fwrite(&stu,sizeof(stu),2,fp);
	if(ret == -1){
		perror("fwrite");
		goto end;
	}else{
		printf("fwrite suceese\n");
	}

	fclose(fp);

	fp = fopen("1.bin","r");
	if (fp == NULL){
		perror("fopen");
		return 0;
	}
	ret = fread(&stu,sizeof(stu),2,fp);
	if(ret == -1){
		perror("fread");
		goto end;
	}
	printf("name1=%s,age1=%d,sex1=%s\n",stu1.name,stu1.age,stu1.sex);
	printf("name2=%s,age2=%d,sex2=%s\n",stu2.name,stu2.age,stu2.sex);
	
end:
	fclose(fp);

	return 0;
}

运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值