我想在写入过程完成后从二进制文件中读取数据,也可以在没有写入过程的情况下读取数据
I wanna read data from my binary file after the writing process complete and also read data without the writing process
这是我编写二进制文件的部分代码。这里我传递一个2d矢量表,其中包含文本格式数据或二进制数据。如果主表包含二进制数据,我想读取并加载到一个向量表中。我已经做过了,如果数据是文本文件,我可以从文件中加载数据,但如果是二进制数据,我不知道如何加载。我也使用索引表。这意味着该表包含主表中每个字段的大小。
例如:emp.idx
field - Size
name - 20
年龄- 2岁
性- 10mainTbl -包含二进制数据的主表。
typedef vector <string> record_t;
typedef vector <record_t> table_t;
table_t mainTbl;
table_t fileStruct::FormatData(table_t &mainTbl)
{
fstream fs("emp.bin",ios::binary | ios::out | ios::in);
size_t rowLength=mainTbl.size();
size_t colLength=idxTbl.size();
count_t colSize;
for (size_t j=0;j<colLength;j++)
{
colSize.push_back(idxTbl[j].fsize);
//cout<<"colum size "<<colSize[j]<<endl;
}
for(size_t i=0;i<rowLength;i++)
{
for (size_t j=0;j<colLength;j++)
{
string data=mainTbl[i].at(j);
data.resize(colSize.at(j),' ');
mainTbl[i].at(j)=data;
int len = data.length();
fs.write(reinterpret_cast<char*> (&len),len);
fs.write(const_cast<char*>(data.c_str()),len);
//cout<<data;
//fu<<mainTbl[i].at(j);
}
fs<<endl;
//cout<<endl;
}
return mainTbl;
}
你的代码写错了
fs.write(reinterpret_cast<char*> (&len),len);
应该fs.write(reinterpret_cast<char*>(&len), sizeof len);
read可以读入临时vector对象,并从中创建string对象。
vector<char> temp;
fs.read(reinterpret_cast<char*>(&len), sizeof len);
if (len > 0)
{
temp.resize(len);
fs.read(&temp[0], len);
}
mainTbl[i].at(j) = string(temp.begin(), temp.end());
相关文章:
- 如何在ros2中从rosbag2读取数据
- OpenCV 和从 OutputArrays 或 (Mat) 读取数据
- 使用C++从磁卡读卡器MT188读取数据
- HDF5 简单读取数据集失败
- 嵌套结构,从由空行分隔的文件中读取数据
- 不要从输入队列套接字读取数据
- 从文件中读取数据,操作员>>
- 如何从excel文件中读取数据并存储到变量中?
- C++:从文件中读取x y数据会产生无限循环吗
- 无法通过FT232RL读取数据
- 如何从QNetworkReply读取数据?
- C++ 逐行从文件(包含空格)读取数据
- 通过显示一行星号来创建条形图,该条形图将读取数据的输入文件
- 我们可以从 TXT 文件中读取数据并使用 C 和 C++ 将其保存到 SQL 数据库吗?
- 从多个 tcp 连接读取数据
- 从文本文件中读取数据并删除所有换行符空格,并在 C++ 控制台中显示
- Qt TCP服务器不从客户端读取数据
- 累积从 C++11 中的文件中读取数据的整数
- 从 txt 文件中读取数据的最简单方法
- 从 txt 文件中读取数据的 Getline