欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++二进制文件读写,以及数据的拼合与还原

程序员文章站 2024-03-18 19:46:04
...

要把数据先合并到一个大的buffer里,然后把这个buffer写成二进制文件,然后重新读取这个二进制文件,然后把数据分配还原

C++二进制文件读写,以及数据的拼合与还原

代码如下:

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main()
{
	//Origin Objects
	vector<int> srcData_01 = { 0, 1, 2, 3, 4, 5 , 6, 7, 8, 9, 10, 11, 12, 13 };
	int srcData_01Size = sizeof(int) * srcData_01.size();

	vector<float> srcData_02 = { 1.1f, 2.1f, 1.5f, 2.3f};
	int srcData_02Size = sizeof(float) * srcData_02.size();

	//StoreBuffer
	vector<char> buffer;
	buffer.resize(srcData_01Size + srcData_02Size);

	//New Objects
	vector<int> destData_01;
	destData_01.resize(srcData_01.size());

	vector<float> destData_02;
	destData_02.resize(srcData_02.size());


	//Origin object to store buffer
	memcpy(buffer.data(), srcData_01.data(), srcData_01Size);
	memcpy(buffer.data() + srcData_01Size, srcData_02.data(), srcData_02Size);

	ofstream writeFile;
	writeFile.open("Files/TestBMP.data", std::ios::out | std::ios::binary);
	if (!writeFile)
	{
		cout << "Error opening file" << endl;
		return 0;
	}
	writeFile.write(buffer.data(), srcData_01Size + srcData_02Size);
	writeFile.close();

	//readBuffer
	vector<char> readbuffer;
	readbuffer.resize(srcData_01Size + srcData_02Size);

	ifstream readFile;
	readFile.open("Files/TestBMP.data", std::ios::in | std::ios::binary);
	if (!readFile)
	{
		cout << "Error opening file" << endl;
		return 0;
	}
	readFile.read(readbuffer.data(), srcData_01Size + srcData_02Size);
	readFile.close();

	//Store buffer to new object
	memcpy(destData_01.data(), readbuffer.data(), srcData_01Size);
	memcpy(destData_02.data(), readbuffer.data() + srcData_01Size, srcData_02Size);

	return 0;
}