-
reading/writing list
I am practicing writing a linked list to disk, and reading the data back into the list. The problem appears to be that the code is not writing the data to disk correctly. Any comments?
#include <iostream>
#include <fstream>
#include <list>
#include <cstdlib>
using namespace std;
class Test {
private:
int a;
int b;
public:
Test( int var1, int var2 ) { a = var1; b = var2; }
Test() { a = 0; b = 0; }
//Test( list<Test>::iterator q ) { a = q->GetA(); b = q->GetB(); }
int GetA() { return a; }
int GetB() { return b; }
};
int main()
{
list<Test> mylist;
list<Test>::iterator p;
ofstream out("C:\\Dev-C++\\Program\\data.txt", ios::out | ios::binary);
ifstream in("C:\\Dev-C++\\Program\\data.txt", ios::in, ios::binary);
// create the data
mylist.push_back(Test(1,2));
mylist.push_back(Test(3,4));
p = mylist.begin();
// write to disk
while( p != mylist.end() ) {
cout << "Writing a record to file...\n";
out.write((char *) &p, sizeof(*p));
p++;
}
mylist.clear(); // destroy the list
in.close();
// read from file into list
mylist.push_back();
p = mylist.begin();
cout << "Reading a record from file...\n";
in.read((char *) &p, sizeof(*p));
while( !in.eof() ) {
mylist.push_back();
p++;
cout << "Reading a record from file...\n";
in.read((char *) &p, sizeof(*p));
}
in.close();
p = mylist.begin();
while( p != mylist.end() ) {
cout << "A: " << p->GetA() << ' ' << p->GetB() << '\n';
p++;
}
system("PAUSE");
return 0;
}
-
You're writing from the address of the iterator, but you should be writing from the address that the iterator points to. This should work -
Code:
#include <iostream>
#include <fstream>
#include <list>
#include <cstdlib>
using namespace std;
class Test {
private:
int a;
int b;
public:
Test( int var1, int var2 ) { a = var1; b = var2; }
Test() { a = 0; b = 0; }
//Test( list<Test>::iterator q ) { a = q->GetA(); b = q->GetB(); }
int GetA() { return a; }
int GetB() { return b; }
};
int main()
{
list<Test> mylist;
list<Test>::iterator p;
ofstream out("data.txt", ios::binary);
ifstream in("data.txt", ios::binary);
// create the data
mylist.push_back(Test(1,2));
mylist.push_back(Test(3,4));
p = mylist.begin();
// write to disk
while( p != mylist.end() ) {
cout << "Writing a record to file...\n";
out.write((char *)&(*p), sizeof(*p));
p++;
}
mylist.clear(); // destroy the list
out.close();
// read from file into list
Test temp;
cout << "Reading a record from file...\n";
in.read((char *)&temp, sizeof(temp));
//mylist.push_back(p);
while( !in.eof() ) {
mylist.push_back(temp);
cout << "Reading a record from file...\n";
in.read((char *) &temp, sizeof(temp));
}
in.close();
p = mylist.begin();
while( p != mylist.end() ) {
cout << "A: " << p->GetA() << ' ' << p->GetB() << '\n';
p++;
}
system("PAUSE");
return 0;
}