繁体   English   中英

将结构写入文件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM