我创建了一个程序来使用 C++ 存储和检索链表,但不幸的是我的程序没有正确检索数据并返回代码 0xC0000005。我的程序有什么问题?我是初学者。
//C++ code
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <ctime>
using namespace std;
struct link
{
link(int dat, link *nxt): data(dat), another(nxt)
{
}
int data;
link *another;
};
struct list
{
link *first;
~list();
list();
void addnew();
void displl();
}list;
list::list()
{
fstream datafile;
datafile.open("datafile", ios::in | ios::app);
datafile.seekg(0, ios::end);
int eb = datafile.tellg();
if(!eb)
{
first = NULL;
return;
}
datafile.seekg(0, ios::beg);
link *head, *current, *preceding;
head = preceding = current = NULL;
while(eb)
{
if(!current)
{
datafile.read((char *)¤t, sizeof(link));
current->another = NULL;
head = current;
}
preceding = current;
datafile.read((char *)¤t->another, sizeof(link));
current = current->another;
current->another = NULL;
preceding->another = current;
eb--;
}
first = head;
}
void list::addnew()
{
srand(time(0) + rand());
first = new link(rand()%10, first);
}
void list::displl()
{
link *current;
cout << endl << " - ";
for(current = first; current; current = current->another)
cout << current->data << " - ";
cout << endl;
}
list::~list()
{
fstream datafile;
datafile.open("datafile", ios::out | ios::app);
link *temp;
while(first != NULL)
{
temp = first;
first = first->another;
datafile.write((char *)&temp, sizeof(link));
delete temp;
}
first = NULL;
}
int main()
{
list.addnew();
list.addnew();
list.addnew();
list.displl();
system("pause");
return 0;
}