C++做二进制文件的读写
将数据保存成二进制文件可以更快。
Talk is cheap,show your the code。
#include <iostream>
#include <fstream>
struct FrameData
{
double data1;
double data2;
double data3;
double data4;
double data5;
};
void generatedata(char* buf)
{
for (int i = 0; i < 100; i++)
{
FrameData data = { i * 0.1, i * 0.2, i * 0.3, i * 0.4, i * 0.5 };
memcpy(buf + i * sizeof(FrameData), &data, sizeof(FrameData));
}
}
void praserdata(char* buf)
{
FrameData data;
for (int i=0; i<100; i++)
{
memcpy(&data, buf + i * sizeof(FrameData), sizeof(FrameData));
}
}
void file_write(char* filename, char* buf, int len)
{
std::ofstream fout(filename, std::ios::binary);
fout.write(buf, len);
fout.close();
}
void file_read(char* filename, char* buf, int* len)
{
std::ifstream fIn(filename, std::ios::binary);
len[0] = 0;
while (!fIn.eof())
{
fIn.read(buf++, 1);
len[0]++;
}
}
int main()
{
char sfilename[] = "testdata.dat";
char datawrite[5000];
char dataread[5000];
int readlen;
generatedata(datawrite);
file_write(sfilename, datawrite, 5000);
file_read(sfilename, dataread, &readlen);
praserdata(dataread);
}