How to store structured data in the Hard Disk?
Hi, I need to have a data structure(container) such as vectors or arrays where I can store data in the memory as well as in the Hard disk. In the following code where I'm writing my fullNames (std::vector<std::vector<std::string>>) in the HDD by making two separate DAT files. I was wondering if there is a better way of doing that. Thanks. #include <iostream> #include <vector> #include <string> #include <iterator> // std::ostream_iterator #include <fstream> void writeToDat() { std::vector<std::vector<std::string>> fullNames{ { "Max", "Wild" }, {"Ellie", "Olson"} }; //main file where data is stored std::vector<std::string> firstNames{}; std::vector<std::string> lastNames{}; for (int i = 0; i < fullNames.size(); i++) { firstNames.push_back(fullNames[i][0]); //filling up firstname lastNames.push_back(fullNames[i][1]); //filling up lastname } std::ofstream ofs_first, ofs_last; ofs_first.open("firstnames.dat", std::ios::out | std::ios::binary); ofs_last.open("lastnames.dat", std::ios::out | std::ios::binary); std::ostream_iterator<std::string> o_iter_first(ofs_first, "\n"); std::ostream_iterator<std::string> o_iter_last(ofs_last, "\n"); std::copy(firstNames.begin(), firstNames.end(), o_iter_first); std::copy(lastNames.begin(), lastNames.end(), o_iter_last); ofs_first.close(); ofs_last.close(); } void readDatFile() { std::vector<std::vector<std::string>> fullNames{}; std::vector<std::string> firstNames{}; std::vector<std::string> lastNames{}; std::ifstream ifs_first("firstnames.dat"); std::ifstream ifs_last("lastnames.dat"); std::string tmp; while (std::getline(ifs_first, tmp)) { firstNames.push_back(tmp); } ifs_first.close(); while (std::getline(ifs_last, tmp)) { lastNames.push_back(tmp); } ifs_last.close(); for (int i = 0; i < firstNames.size(); i++) fullNames.push_back({ firstNames[i], lastNames[i] }); //recreating fullnames for (std::string i : fullNames[1]) std::cout << i << std::endl; }