Without seeing where you are writing to the file, I can't suggest a fix, however I can suggest an alternative.
Serialization[
^]. The idea is that each class/struct is responsible for saving/restoring its own data, which really simplifies things.
#include <stdio.h>
#include "stdafx.h"
#include<iostream>
#include<conio.h>
#include<fstream>
using namespace std;
struct node {
node *next;
int Id;
node(int id) : next(NULL), Id(id) { } void serialize(ostream &s) {
s.write((char *)&Id, sizeof(Id));
if (next != NULL) {
next->serialize(s);
}
}
static node *unserialize(istream &s) {
int i;
s.read((char *)&i, sizeof(i));
if (s.eof()) {
return NULL;
}
node *n = new node(i);
n->next = unserialize(s);
return n;
}
};
class LL {
node* first;
node* last;
public:
LL() : first(NULL), last(NULL) { } ~LL() {
node *n = first;
while (n != NULL) {
node *del = n;
n = n->next;
delete del;
}
}
void add(int i) {
if(first == NULL) {
first = new node(i);
last = first;
} else {
node *temp = new node(i);
last->next = temp;
last = temp;
}
}
void show() {
node *tfirst = first;
while (tfirst != NULL) {
cout<<"ID "<<tfirst->Id<<endl;
tfirst = tfirst->next;
}
}
void serialize(ostream &s) {
if (first != NULL) {
first->serialize(s);
}
}
static LL *unserialize(istream &s) {
LL *ll = new LL();
ll->first = node::unserialize(s);
ll->last = ll->first;
return ll;
}
};
int _tmain(int argc, _TCHAR* argv[]) {
LL *ll = new LL();
ll->add(1);
ll->add(2);
ll->add(4);
ll->add(3);
cout << "Original list:" << endl;
ll->show();
fstream fs;
fs.open("Malik.txt", ios::out|ios::binary|ios::app);
ll->serialize(fs);
delete ll;
fs.close();
fs.open("Malik.txt", ios::in|ios::binary|ios::app);
cout << "Saved list:" << endl;
ll = LL::unserialize(fs);
ll->show();
delete ll;
fs.close();
return 0;
}
Also, you could use
Templates[
^] for this, which would make it a little more dynamic, if you need lists of multiple data types.