I am trying to write a std::vector<std::string> to file and read it out again.
The writing looks like this:
std::ifstream f(fname, std::ios::binary);
num = _resultColumnNames.size();
f.write(reinterpret_cast<const char*>(&num), sizeof(size_t));
for (size_t i = 0; i < num; i++) {
std::string resultColumnName = _resultColumnNames[i];
size_t resultColumnNameLength = resultColumnName.length();
f.write(reinterpret_cast<const char*>(&resultColumnNameLength), sizeof(size_t));
f.write(resultColumnName.c_str(), resultColumnNameLength);
}
- Get the vector size to know how many
std::stringto write - Write the size to file
- For every
std::stringwrite its length and characters to file
The reading looks like this:
f.seekg(posResultColumnNames);
for (size_t i = 0; i < numResultColumnNames; i++) {
size_t resultColumnNameLength;
std::string resultColumnName;
f.read(reinterpret_cast<char*>(&resultColumnNameLength), sizeof(size_t));
resultColumnName.reserve(resultColumnNameLength);
f.read(reinterpret_cast<char*>(&resultColumnName[0]), resultColumnNameLength);
LOG(INFO) << "[GEOMCACHE] resultColumnNameLength: " << resultColumnNameLength;
LOG(INFO) << "[GEOMCACHE] resultColumnName: " << resultColumnName;
}
- Seek to where the data begins
- Read the
std::stringlength - Reserve that many characters for the
std::string - Read the characters
The length of the std::string is properly read for every std::string, but the std::string itself is always empty. I don't know if it already goes wrong when writing the data or if it is only a reading problem. Does someone know why this doesn't work? Thank you!