c++二进制文件的读写

#include<iostream>
#include<string>
#include<fstream>//文件流工具类头文件
using namespace std;

class Person {
public:
	int a;
	char str[64];
};
void test1() {

	//1,包含头文件fstream

	//2,创建文件流对象
	ofstream ofs("wxd.txt", ios::out | ios::binary|ios::trunc);

	//3,打开文件流对象

	//4,写数据 “<<”
	Person p = { 18,"王五" };


	cout << p.a << " " << p.str << endl;
	ofs.write((const char*)&p, sizeof(Person));

	//5,关闭文件流对像
	ofs.close();

}
void test() {
	//1,包含头文件fstream

	//2,创建文件流对象
	ifstream ifs("wxd.txt", ios::in | ios::binary);

	//3,打开文件流对象

	if (!ifs.is_open()) {
		cout << "文件打开失败" << endl;
		return;
	}
	//4,写数据 “<<”
	Person p;

	ifs.read((char*)&p, sizeof(Person));
	cout << p.a << " " << p.str << endl;
	//5,关闭文件流对像
	ifs.close();

}

int main() {
	test();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中,我们可以使用文件流来二进制文件。以下是一个简单的示例: 二进制文件: ```c++ #include <iostream> #include <fstream> int main() { std::ofstream outfile("data.bin", std::ios::binary); if (outfile.is_open()) { int number = 10; outfile.write(reinterpret_cast<const char*>(&number), sizeof(number)); outfile.close(); } else { std::cerr << "Unable to open file for writing" << std::endl; } return 0; } ``` 首先,我们使用`std::ofstream`来打开一个文件,指定文件名和打开方式`std::ios::binary`。然后,我们使用`write()`函数来入一个整数。`reinterpret_cast`用于将整数指针强制转换为字符指针,以便在文件中将其入为字节。最后,我们关闭文件二进制文件: ```c++ #include <iostream> #include <fstream> int main() { std::ifstream infile("data.bin", std::ios::binary); if (infile.is_open()) { int number; infile.read(reinterpret_cast<char*>(&number), sizeof(number)); std::cout << "Number: " << number << std::endl; infile.close(); } else { std::cerr << "Unable to open file for reading" << std::endl; } return 0; } ``` 我们使用`std::ifstream`打开文件,指定文件名和打开方式`std::ios::binary`。然后,我们使用`read()`函数来取整数。`reinterpret_cast`用于将字符指针强制转换为整数指针,以便从文件取字节并将其转换为整数。最后,我们关闭文件并输出取的整数。 需要注意的是,在二进制文件时,我们需要注意数据的字节顺序(大端序或小端序),以免在不同的平台上出现问题。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值