关于二进制文件fread、fwrite函数使用读写 分类: C语言学习 ...

环境:vs2013

语言:C语言

时间:2015年3月10日

功能:实现二进制文件的读写实例

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define FILENAME "d:/studentInfo"
#define COUNT 5
typedef struct
{
	char name[10];
	short Math;
	short Chinese;
	short WenZong;
}Student;

//读二进制文件信息
int ReadInfo();
//写入二进制文件信息中
int WriteInfo(Student  *stu,int count);
//初始化学生信息
int InitInfo(Student *stu,int count);
int main(void)
{
	int resWrite = 0,resRead=0;
	Student stu[COUNT];
	InitInfo(stu, COUNT);
	resWrite = WriteInfo(stu, COUNT);
	if (0 == resWrite)
		printf("写入成功\n");
	else
		printf("写入失败\n");
	
	ReadInfo();
	system("pause");
	return 0;
}

//初始化学生信息
int InitInfo(Student *stu, int count)
{
	int res = 0;
	if (NULL == stu || count < 0)
	{
		res = -1;
		return res;
	}
	for (size_t i = 0; i < count; i++)
	{
		sprintf((stu+i)->name,"LSX%d",i);
		(stu + i)->Math = i * 5 + 100;
		(stu + i)->Chinese = i * 5 + 80;
		(stu + i)->WenZong = i * 5 + 200;
	}
	return res;
}

//读二进制文件信息
int ReadInfo()
{
	int res = 0,res2=0;
	FILE*fp = NULL;
	Student stu[1];
	fp = fopen(FILENAME,"rb");  //读二进制文件,如果不存在,就错误
	if (NULL == fp)
	{
		res = -1;
		return res;
	}
	while (!feof(fp))
	{
		res2= fread(stu,sizeof(Student),1,fp); //fread函数的返回值很重要,它的返回值就是第三个参数的值,如果不一致就发生错误
		if (1 == res2)
		{
			printf("%s %10d %10d %10d",stu->name,stu->Math,stu->Chinese,stu->WenZong);
		}
		printf("\n");
	}
	if (NULL != fp)
		fclose(fp);
	return res;
}


//写入二进制文件信息中
int WriteInfo(Student * stu,int count)
{
	int res = 0,res2=0;
	FILE*fp = NULL;
	if (NULL == stu || count<0)
	{
		res = -1;
		return res;
	}
	fp = fopen("d:/studentInfo", "wb");  //写二进制文件,不存在就重新建立文件
	if (NULL == fp)
	{
		res = -1;
		return res;
	}
	for (size_t i = 0; i < count; i++)
	{
		res2 = fwrite(stu + i, sizeof(Student), 1, fp);// fwrite函数的返回值很重要,它的返回值就是第三个参数的值,如果不一致就发生错误
		if (1 != res2)
		{
			res = -1;
			return res;
		}
	}
	if (NULL != fp) //关闭文件
		fclose(fp);
	return res;
}




版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/L-Lune/p/4671284.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值