dimanche 19 mai 2019

Write a struct to a file

I am working on an assignment, building a persistent b+ tree index on a csv file. I have read in the CSV file, and placed the data that I want to write to the datafile in a deque of structs.

deque<employeeShort> employees

struct employeeShort {
    int Emp_ID;
    string firstname;
    string lastname;
    string SSN;
    string username;
    string password;
};

I now need to write this entire deque to a file (note there are about 10000 entries). But to my understanding I can only write to the file through the buffer which is a char array.

My current solution is to loop through the entire deque and add to a char vector which I can then convert to a character array and use to write to the file.

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));

I know this is a very hacky way of doing it and I was hoping someone could suggest something more efficient. Thank you.

Aucun commentaire:

Enregistrer un commentaire