C++读取二进制文件到二维数组并保存到文本文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AnonymousRookie/article/details/46011683
#include <iostream>
using namespace std;
#include <fstream>
#include <math.h>
#include <random>
#include <stdint.h>
#include <queue>

struct IMUData
{
	float Roll;
	float Pitch;
	float Yaw;
};

IMUData imuData;

queue<IMUData> ImuQueue;


uint32_t FileLength, Index;
float** IMUBuffer;


void operator << (ostream& Out,const IMUData& Obj)
{
	Out<<Obj.Pitch<<","<<Obj.Roll<<","<<Obj.Yaw<<"\n";
}


template <class T>
void downLoadData(queue<T> Buf,const char *fileName)//把队列中的数据写入文件
{ 
	ofstream  fout(fileName); 
	while(!Buf.empty())
	{
		operator << (fout,Buf.front());
		Buf.pop();
	}
	if(Buf.empty()){
		cout<<"\nNow the Buffer is Empty!\n"<<endl;
	}
}


bool IMUInit() {
	std::ifstream ScanSet ("imu.bin",std::ifstream::binary);
	if (ScanSet.is_open()) {
		ScanSet.seekg(0,ScanSet.end);
		FileLength = uint32_t(ScanSet.tellg());
		//FileLength:文件大小,FileLength/n:文件数据的行数,n:每行记录的大小
		cout<<"FileLength = "<<FileLength<<"\tFileLength/12 = "<<FileLength/12<<endl;
		ScanSet.seekg(0,ScanSet.beg);

		IMUBuffer = new float*[FileLength/12];
		for (uint32_t i = 0; i < FileLength/12; i++) {
			IMUBuffer[i] = new float[3];
			ScanSet.read((char*)IMUBuffer[i],12);
			//cout<<IMUBuffer[i][0]<<endl;
		}
		ScanSet.close();
	} else {
		return false;
	}
	return true;
}
float* GetValues() {
	if (Index >= FileLength/12) {
		return NULL;
	}
	return IMUBuffer[Index++];
}



int main()
{
	if(IMUInit()){
		float* buf;

		for(int i=0;i<FileLength/12;++i){
			buf = GetValues();
			//cout<<buf[0]<<"\t"<<buf[1]<<"\t"<<buf[2]<<"\t"<<endl;
			imuData.Pitch = buf[0];
			imuData.Roll = buf[1];
			imuData.Yaw = buf[2];
			ImuQueue.push(imuData);
		}
	}
	else{
		cout<<"error!!!"<<endl;
	}

	downLoadData(ImuQueue,"ImuDataFile.txt");

	return 0;
}

展开阅读全文

没有更多推荐了,返回首页