[英]Write a struct to a file
我正在進行一項任務,在csv文件上構建一個持久的b +樹索引。 我已經閱讀了CSV文件,並將我想要寫入的數據放在結構的雙端隊列中。
deque<employeeShort> employees
struct employeeShort {
int Emp_ID;
string firstname;
string lastname;
string SSN;
string username;
string password;
};
我現在需要將整個deque寫入文件(注意大約有10000個條目)。 但據我了解,我只能通過緩沖區寫入文件,這是一個char數組。
我目前的解決方案是循環遍歷整個deque並添加到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));
我知道這是一種非常黑客的做法,我希望有人能提出更有效的建議。 謝謝。
如果我已經很好理解,您希望將存儲在deque
所有數據結構寫入文件中。
對我來說,你只需要用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
以不刪除文件中的先前內容,但是如果要在寫入數據之前清除文件,則只需刪除此參數(通過默認情況下,它會在打開時清除文件的先前內容。
我希望它可以提供幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.