关于二进制文件fread、fwrite函数使用读写 分类: C语言学习 2015-03-10 22:05 201人阅读 评论(0) 收藏

环境: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("写入成功
");
	else
		printf("写入失败
");
	
	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("
");
	}
	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