【C++】二进制文件向硬盘的输出和读入

本文通过C++实现了一个简单的文件读写程序,利用结构体存储学生信息,并使用ofstream和ifstream进行二进制文件的写入与读取操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

输出“stud.dat” :

#include <fstream>
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "io.h" 
#include<iostream>




using namespace std;
struct student
{
	char name[20];
	int num;
	int age;
	char sex;
};
int main()
{
	student stud[3] = { "Li", 1001, 18, 'f', "Fun", 1002, 19, 'm', "Wang", 1004, 17, 'f' };
	ofstream outfile("stud.dat", ios::binary);
	if (!outfile)
	{
		cerr << "open error!" << endl;
		abort();//退出程序
	}
	for (int i = 0; i<3; i++)
		outfile.write((char*)&stud[i], sizeof(stud[i]));
	outfile.close();
	cout << sizeof(stud[0].name) << endl;
	return 0;
}

 

读入“stud.dat” :

#include <fstream>
#include "stdlib.h"
#include "stdio.h"
#include "io.h" 
#include<iostream>
#include <string>
using namespace std;
struct student
{
	char name[20];
	int num;
	int age;
	char sex;
};
int main()
{
	student stud[3];
	int i;
	ifstream infile("stud.dat", ios::binary);
	if (!infile)
	{
		cerr << "open error!" << endl;
		abort();
	}
	for (i = 0; i<3; i++)
		infile.read((char*)&stud[i], sizeof(stud[i]));
	
	for (i = 0; i<3; i++)
	{
		cout << "NO." << i + 1 << endl;
		cout << "name:" << stud[i].name << endl;
		cout << "num:" << stud[i].num << endl;
		cout << "age:" << stud[i].age << endl;
		cout << "sex:" << stud[i].sex << endl;
	}
	infile.close();
	return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值