Saving a vector of strings to disk not working as expected. I see that that file is created but with 0 bytes and no entries. Note: I compile C++ code on a MAC OS on Xcode (v4.3.3).
Declaration of the vector and the string:
vector<string>taskVector;
string newTaskEntry;
This is how I add new strings to the array while program is running:
taskVector.push_back(newTaskEntry);
When user exit the program I do this:
fstream file;
file.open("data.txt", ios::out | ios::trunc);
for (int i = 0; i > taskVector.size(); i++) {
file.write(taskVector[i].c_str(), taskVector[i].length());
file.close();
Any idea why I don't see any entries? Second of all, can you give me a hint how to read the data back in when I'm able to save the content to disk?
First (like @Nim mentioned) you did your check wrong:
for (int i = 0; i > taskVector.size(); i++) {
should by
for (int i = 0; i < taskVector.size(); i++) {
Second: take the close out of the loop:
for (int i = 0; i > taskVector.size(); i++) {
file.write(taskVector[i].c_str(), taskVector[i].length());
}
file.close();
And about reading them back in: Right now, you save no information, where your strings end, or how long they are. Without that, you'll have to guess, where the strings and (and how many they are). I would recomend one of the following:
Either take a termination byte, that indicates, when a string ends in your file. '\0'
would be an idea. But you must make sure, it is not present in your strings, or you cannot recrate them correctly. When reading back, split at that char.
The other way would be to store the length information of the strings in front of the strings. You could store an unsigned int of 4 bytes in front befor storing the string. Then, when reading back, you first read back the 4 byte string, then you read the amount of bytes that number indicates. Problems: you need to decide, how long your strings can be at max (with 4 bytes of length information, that's about 4.8 * 10^9 bytes, pretty much). And you might check on the byte order of your system (big endian vs little endian), if you plan to use it on different computers.