STL & io

please help me how can i store data of a list to binary file?!
for exmple :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void main()
{
	list<int> l;
	ofstream fout("a", ios::out | ios::binary );

	for (int i = 0; i < 5; i++)
		l.push_back( i );

	list<int>::iterator itr;

	for (itr = l.begin(); itr != l.end(); ++itr)
		fout.write((const char *)&itr, sizeof( itr ));

	fout.close();
}


but it doesnt work correctly because if i use

fin.read((char *)&itr, sizeof( itr ));
then itr is garbage !!

i dont know how can i save data of a list or set or ... to binary file !!! please help me
You're not using iterator correctly. For example, if you wanted to print all numbers in a list, you'd write cout << *itr;, right? So the object in the list is *itr. The address of that object is &*itr, the size of that object is sizeof(*itr). What you are writing now is the iterator itself and not the value it points to.
tnx i do but dont work !!!

my code is
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void main()
{
	list<int> l;
	ofstream fout("a", ios::out | ios::binary );

	for (int i = 0; i < 5; i++)
		l.push_back( i );

	list<int>::iterator itr;

	for (itr = l.begin(); itr != l.end(); ++itr)
		fout.write((const char *)&*itr, sizeof( *itr ));

	fout.close();

	ifstream fin("a", ios::in | ios::binary);
	for (int i = 0; i < 5; i++)
	{
		fin.read((char *)&*itr, sizeof( *itr ));   // exception !!!!
		cout << *itr << endl;
	}

	cin.get();
	fin.close();
}


but dont work :( i want store object of one list and then read all of them
im try to store iterator itself with

fout.write((const char *)&itr, sizeof( itr ));

and then read itself iterator but doesent work
The iterator is a pointer, basically. It's like trying to save pointers - of course that won't work.
iterator is one class that works like pointer !!! exactly not pointer !!!
1
2
3
4
5
6
7
8
9
10
for (itr = l.begin(); itr != l.end(); ++itr)
		//something

//here itr==l.end()
	ifstream fin("a", ios::in | ios::binary);
	for (int i = 0; i < 5; i++)
	{
		fin.read((char *)&*itr, sizeof( *itr ));   // dereferencing a l.end()
		cout << *itr << endl;
	}
tnx alot very very tnx.

when i read from file before i must initialize iter with value like l.begin() then *itr dont break.

but if i clear list , i cant read from file !!!
Last edited on
no body know how can STORE object of a list to file

and READ them from file !!!!!!!!!!!!!!!
Topic archived. No new replies allowed.