C++按位写入/读取文件

#include<fstream>
#include<string>
#include<iostream>
using namespace std;
int main() {


	ofstream 输出文件("test.bin", ios::out | ios::binary);
	string test = "Hello,world!";
	int length = test.size();
	输出文件.write((char *)&length, sizeof(int));
	输出文件.write(test.c_str(), test.size());
	输出文件.close();

	ifstream templates_in("test.bin", ios::in | ios::binary);

	int 读入长度;
	std::string 内容;
	templates_in.read((char*)&读入长度, sizeof(int));
	内容.resize(读入长度);
	templates_in.read((char*)&内容[0], 读入长度);
	std::cout << 内容;
	system("pause");


}

猜你喜欢

转载自blog.csdn.net/zmdsjtu/article/details/79936918