Hi, I've been trying to create program that can access a binary file with a vector in it without first saving it to the file. If I just try to read from the file without saving something, the vector will have information in it but when I output it to screen it will be either gibberish or not output at all. If I do save information to the file in the same program as when I read from it, the output will be what I want. Here is my code:

#include <iostream>
#include <vector>
#include <conio>
#include <fstream>
#include <vcl.h>
//-----------------------------------------------------------------------
struct strWord{
           string word;
           string type;
           string tense;
}aWord;
vector<strWord> words;
vector<strWord> wordsB;
//--------------------------------------------------------------------------
int main(){
          aWord.word = "cow"; 
          aWord.type = "noun"; 
          aWord.tense = "singular";

          words.push_back(aWord);

          ofstream out("BinaryDict.txt", ios::binary);
          out.write((char*)&words, sizeof(words));
          out.close();
          
          ifstream in("BinaryDict.txt", ios::in | ios::binary);
          while(!in.eof()){
                    in.read((char*)&wordsB, sizeof(wordsB));
          }
          in.close();

          cout << wordsB[0].word << '\n';
          cout << wordsB[0].type << '\n';
          cout << wordsB[0].tense << '\n';

          getch();
}

It's totally wrong approach: class std::vector object is not the same as its contents, sizeof(words) does not bear a relation to the contained data size (print sizeof(words) value, it's constant). Never serialize/deserialize STL containers (include std::string) in a such manner.

Probably the simplest way to serialize your struct strWord object is to output it as three text lines to a text (not binary) fstream. To serialize a vector of n strWord repeat this operation n times. Now to deserialize this vector (to load it in the memory) make reverse operations.

PS. Think: a std::string object contains a string size (unsigned int) and a pointer to its contents. You have wrote only this "header" and this pointer value is absolutely senseless when you will load it into the memory (especially for the next run).

Ok. I see what you meant about sizeof(words) being constant. Thanks a lot.

This article has been dead for over six months. Start a new discussion instead.