trouble reading binary data file
Hi,
I was hoping to get some help to understand why I have coded this so poorly. I have re written the code below to demonstrate the problem I face. A really good indicator that something is wrong is the fact that it crashes 50% during run time.
I would like to know why it crashes half the time ? what conditions had changed to make it execute okay the other times.
My main problem is that I had thought this had successfully written to file. As i have tested, by reading it back.
But if I remove my output to file code and only try to import my file (previously created) it recognizes there are two elements but can't output its data.
I am using code::blocks 10.05.
btw, I was only wanting to do this as a learning experience with binary files I do understand I could use a text file. Should I not be using binary files with string.
Many thanks in advance for your help.
Code:
#include <iostream>
#include <vector>
#include <fstream>
// Demonstrating my problem with reading from binary from file
using namespace std;
int main()
{
vector<string> newBuffer; // will output file from here
vector<string> tempBuffer; // will input file into here
string testing = "hello world\n";
tempBuffer.push_back(testing);
tempBuffer.push_back(testing);
// output to file
///*
ofstream fout ("file1", ios::binary);
if(!fout)
{
cout << "unable to open file\n";
}
fout.write( (char*) &tempBuffer,sizeof tempBuffer); // casting char*
fout.close();
tempBuffer.clear();
//*/
// read from file put into new vector
ifstream fin ("file1", ios::binary);
if(!fin)
{
cout << "unable to open file\n";
}
fin.read( (char*) &newBuffer,sizeof newBuffer);
fin.close();
// reading new vector
cout << "newBuffer size " << newBuffer.size() << "\n";
for (unsigned short x =0;x<newBuffer.size();x++)
cout << (string) newBuffer[x];
newBuffer.clear();
return 0;
}