tab.write((char*)&words[i], 20);
Explain exactly what you want to write to the file? If the garbage, then it is he who writes it there, quite successfully.
To preserve such complex structures as the plus vector, you cannot write raw data. This is the service information of the vector class itself, which has nothing to do with your data. For each type of data stored in a vector, it is necessary to develop the means of recording independently. The easiest way, of course, is to write this type of data as text:
for(size_t i = 0; i < words.size(); i++) { tab << words[i] << "\n" << i << "\n"; }
Or even simpler (why write a sequence number, if the lines go in order anyway?):
for(size_t i = 0; i < words.size(); i++) { tab << words[i] << "\n"; }
But if you just want the binary format, then somehow, for example (do not forget that the lines are of different lengths):
fstream tab("tab.txt", ios::binary | ios::out); for(size_t i = 0; i < words.size(); i++) { size_t size = words[i].size(); // пишем в файл длину строки: tab.write( (char *)&size, sizeof(size) ); // теперь саму строку: tab.write( words[i].c_str(), size ); } tab.close();
Well, read:
fstream show("tab.txt", ios::binary | ios::in); for( size_t i = 0; i < words.size(); i++ ) { size_t size; // читаем длину очередной строки: show.read( (char *)&size, sizeof(size) ); // читаем саму строку: char buf[size + 1]; show.read( buf, size ); buf[size] = 0; // нечётные записи пропускаем: if( !(i % 2) ) { // с чётными что-то делаем: cout << i < ": " << buf << "\n"; } } show.close();
To make entries of one length, you can first calculate the maximum length of the string in the vector, and create entries as structures:
struct _rec { size_t order; char word[1]; } *rec = (_rec *)new char[ sizeof(_rec) + N ]; for( size_t i = 0; i < words.size(); i++ ) { memset( rec->word, 0, N+1 ); strcpy( rec->word, words[i].c_str() ); rec->order = i; // не знаю что сюда писать и откуда брать tab.write( (char *)rec, sizeof(_rec)+N ); }
Well:
for( size_t i = 0; i < words.size(); i++ ) { show.read( (char *)rec, sizeof(_rec)+N ); cout << rec->order << ": " << rec->word << "\n" }
PPS It is possible, of course, then all this (reading and writing elements) can be written as operator << and operator >> .