Why program crashes when reading linked List from file?

Why program crashes when reading linked List from file?
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>  
#include <fstream>  
using namespace std;  



struct link{  
	int data;  
	link* next;  
};  

class linkedList{  
public:  
	linkedList();  
	void addItem(int);  
	void print(void);  
private:  
	link* head;  
	link* tail;
};  

linkedList::linkedList(){  
	head = tail = NULL;  
}  

void linkedList::addItem(int n){  
	link* temp = new link;  
	temp->data = n; 
	temp->next = 0;

	if (head == 0 && tail == 0){
		head = temp;
		tail = temp;
	}
	else{
		tail->next = temp;
		tail = temp;
	} 
	ofstream os("linkedList.txt",ios::binary | ios::out | ios::app);
	os.write(reinterpret_cast<char*>(&temp),sizeof(temp));  
}  

void linkedList::print(){  
	for (link* p = head; p != NULL; p = p->next){  
		cout << p->data << endl;  
	}  
}  

int main(){  
	int n;   
	
	linkedList ll;  
	
	do{  
		cout << "Enter number to insert: (-1 to print): "; cin >> n;  
		
		ll.addItem(n);  
	} while (n != -1);  
    
	ll.print();  

	cout << "Linked List has been written in the file and has been printed.";
        //*****MY Program crashes here ****
	//READING LINKED LIST FROM FILE.
	//////////////
	linkedList LL;
		ifstream is("linkedList.txt", ios::binary | ios::in);
		while (is){
			is.read( reinterpret_cast<char*>(&LL), sizeof(linkedList) );
			LL.print();
			cout << "\n\n";
		}
	return 0;  
}  
Last edited on
Do you understand what write and read is doing?
Write and read are writing/reading the whole pointer to the file. What I know.
line 40 is wrong, it should be os.write(reinterpret_cast<char*>(temp),sizeof(*temp));

Your reading code is also wrong. You recorded the content of the nodes. Yet it's the whole linked list object you overwrite when you read. That won't work.
You have to create a new "link", load the file data into it and then insert the "link" into the list.
Thanks toum!
Last edited on
Topic archived. No new replies allowed.