0

Hi everyone, I'm new to this forum and it has helped me a lot with the project I am currently working on.

Using VS2008 and created an MFC dialog based application. I just started learning C++ and am finding it difficult to solve this problem.

What I'm trying to do is store a vector into a binary file and then read the binary file back into a vector. I have 3 strings that I am storing into an object and then create a vector of these objects. Each element in the vector therefore consists of 3 strings (date, article1, article2). My code is like this:

class Article 
{	
public:
	char date_time[19];
	CString article1;
	CString article2;
};

Write to file:

vector<Article> articles;
Article articleItems; 
strcpy(articleItems.date_time, buf); 
articleItems.article1 = n_Articles;
articleItems.article2 = w_Articles; 

articles.push_back(articleItems);

ofstream articleFile;
articleFile.open("articles.dat", ios::out|ios::binary|ios::app);
articleFile.write(reinterpret_cast<char *>(&articles), sizeof(articles));
articleFile.close();

Read from file:

vector<Article> articleItems; 
ifstream articles; 
articles.open("articles.dat", ios::in|ios::binary);
articles.read(reinterpret_cast<char *>(&articleItems), sizeof(articleItems));
articles.close();

Writing seemed to create a file, but then reading produced no results (nothing in the vector). If I wrote 'articleItems' object to the file instead of the vector, then I could read this properly if I was reading it into another object of type 'Article'. However when exiting the application, the program would crash with a 'Access violation error' and the data in the file would get corrupted? (won't display properly if I tried to read the same file again).

I had to change date_time from a string to char because it wouldn't display properly when reading the file (weird characters - if a string is used, instead of char).

I'm trying to create a vector so I could search for articles by date and then pull out these articles and display them, but having problems with saving vectors to files!

Hope you can help, thanks!

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by abbz375
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.