c++ - 将结构写入文件
问题描述
我正在处理一项任务,在 csv 文件上构建一个持久的 b+ 树索引。我已读入 CSV 文件,并将要写入数据文件的数据放在结构的双端队列中。
deque<employeeShort> employees
struct employeeShort {
int Emp_ID;
string firstname;
string lastname;
string SSN;
string username;
string password;
};
我现在需要将整个双端队列写入文件(注意大约有 10000 个条目)。但据我了解,我只能通过缓冲区写入文件,缓冲区是一个字符数组。
我当前的解决方案是遍历整个双端队列并添加到一个 char 向量中,然后我可以将其转换为字符数组并用于写入文件。
vector<char> bufferVec;
while(!employees.empty()) {
readCSV::employeeShort tempEmp = employees.front();
string tempID = to_string(tempEmp.Emp_ID);
copy(tempID.begin(), tempID.end(), back_inserter(bufferVec));
copy(tempEmp.firstname.begin(), tempEmp.firstname.end(), back_inserter(bufferVec));
copy(tempEmp.lastname.begin(), tempEmp.lastname.end(), back_inserter(bufferVec));
copy(tempEmp.SSN.begin(), tempEmp.SSN.end(), back_inserter(bufferVec));
copy(tempEmp.username.begin(), tempEmp.username.end(), back_inserter(bufferVec));
copy(tempEmp.password.begin(), tempEmp.password.end(), back_inserter(bufferVec));
employees.pop_front();
}
char buffer[bufferVec.size()];
copy(bufferVec.begin(), bufferVec.end(), buffer);
pageFile.global_fs.write(buffer, sizeof(buffer));
我知道这是一种非常老套的方法,我希望有人能提出更有效的建议。谢谢你。
解决方案
如果我很好理解,您想将存储在 a 中的所有数据结构写入deque
文件。
对我来说,您只需要使用 a 打开文件std::ofstream
并遍历您的双端队列即可将其内容写入文件。
例子:
C++ 代码:
#include <fstream>
#include <iostream>
#include <deque>
struct data
{
char s1;
std::string s2;
int s3;
};
int main()
{
std::deque<data> data_deque;
data_deque.push_back(data{'A', "Zero", 0});
data_deque.push_back(data{'B', "One", 1});
data_deque.push_back(data{'C', "Two", 2});
std::string file_path("data.txt"); // The path to the file to be written
std::ofstream out_s(file_path, std::ofstream::app);
if(out_s)
{
for(const data & d : data_deque)
{
out_s << "S1: " << d.s1 << '\n';
out_s << "S2: " << d.s2 << '\n';
out_s << "S3: " << d.s3 << '\n';
out_s << std::endl; // separate each data by a new line;
}
out_s.close();
}
else
std::cout << "Could not open file: " << file_path << std::endl;
return 0;
}
data.txt 中的输出:
S1:A
S2:零
S3:0
S1:B
S2:一个
S3:1
S1:C
S2:两个
S3:2
在创建时std::ofstream
,我添加std::ofstream::app
了不擦除文件中以前的内容,但是如果您想在写入数据之前清理文件,您只需删除此参数(默认情况下,它会清除文件中的先前内容)开)。
我希望它可以帮助。
推荐阅读
- android-studio - 设置 DevTools 失败(Flutter Inspector)
- css - 底部弯曲的 HTML 元素
- perl - 如何使用 Perl 语言在新的 Elasticsearch 中使用聚合框架
- css - 为什么使用 SASS 的 Angular 项目不起作用?
- laravel - 从 json 响应水平创建表
- qt3d - 如何在 QT3D 中在一帧中只渲染一次实体或图层
- r - 使用索引文件时闪亮的应用程序不会显示图表
- java - org.springframework.orm.jpa.JpaSystemException:通过持久属性的反射访问字段时出错
- java - HTTPS TLS 1.2 使用 Wildfly
- apache-storm - 如何清理风暴中死亡的工作日志?