所以,我正在做一个程序,涉及多个链接列表,就像一个bellow,我试图做的是保存某个链接列表中的节点,以防止程序崩溃,并读取二进制文件,所以我不松散的节点,id已经添加.我只是不知道如何做到这一点。
void LinkedList::saveOn(std::ostream& os) {
Node* temp = head;
while (temp != NULL) {
os << temp->data;
temp = temp->next;
}
}
但我不知道这样做是否可行,以及如何从文件中读回。
class Node {
public:
int code;
doble price;
string name;
Node* next;
};
class LinkedList{
public:
LinkedList() { // constructor
head = NULL;
}
~LinkedList() {}; // destructor
void addNode(int val);
void reverseList();
void display();
private:
Node* head;
};
// function to add node to a list
void LinkedList::addNode(int val) {
Node* newnode = new Node();
newnode->data = val;
newnode->next = NULL;
if (head == NULL) {
head = newnode;
}
else {
Node* temp = head; // head is not NULL
while (temp->next != NULL) {
temp = temp->next; // go to end of list
}
temp->next = newnode; // linking to newnode
}
}
// reverse Linked List
void LinkedList::reverseList() {
Node* temp = head;
Node* nextnode = NULL;
Node* revnode = NULL;
while (temp != NULL) {
head = temp;
nextnode = temp->next;
temp->next = revnode;
revnode = temp;
temp = nextnode;
}
}
void LinkedList::display() {
if (head == NULL) {
cout << "List is empty!" << endl;
}
else {
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
}
由于你的 "Node "对象是固定大小的,你应该可以只把原始数据(即int)写入一个文件(没有任何空格)。下一个 "指针不必保存,因为当你从文件中重新创建链接列表时,它将会改变。
当你想重新创建链接列表时,只需将整个文件读到一个缓冲区,并在你还没有到达缓冲区末端时继续创建新元素。
例如:要写。
Node* current = head;
FILE* fp = fopen("save.bin", "wb");
while (current != NULL) {
fwrite(¤t->data, sizeof(int), 1, fp);
current = current->next;
}
fclose(fp);
要读。
FILE* fp = fopen("save.bin", "rb");
int newData;
while (fread(&newData, sizeof(int), 1, fp) > 0) {
addNode(newData);
}
fclose(fp);
现在我知道你想存储字符串, 你可以存储每个节点 作为一个单一的行 你可以做以下工作:
To Write:
Node* current = head;
FILE* fp = fopen("save.bin", "wb");
while (current != NULL) {
fwrite(¤t->code, sizeof(int), 1, fp);
fwrite(¤t->price, sizeof(double), 1, fp);
// The string (plus the null byte)
fwrite(current->name.c_str(), sizeof(char), current->name.length() + 1, fp);
// newline to indicate new node
if (current->next != NULL)
fprintf(fp, "\n");
current = current->next;
}
fclose(fp);