【发布时间】:2017-07-27 12:08:01
【问题描述】:
我对文件处理的概念很陌生。我正在尝试制作一个待办事项列表,以跟踪文件中的每个修改。我不确定如何实现这一点,所以我制作了一个简单的链表并尝试将其读取并写入文件,但我失败了。 这是我的代码->
#include <iostream>
#include <fstream>
struct node{
int val;
node *next = NULL;
};
void add(node *&head, int val){
node *newPtr = new node;
if(head==NULL){
newPtr->val = val;
head = newPtr;
}
else{
newPtr->val = val;
newPtr->next = head;
head = newPtr;
}
}
void print(node *head){
node *temp;
temp = head;
while(temp!=0){
std::cout << (*temp).val << " ";
temp = temp->next;
}
std::cout << std::endl;
}
int main(){
node *head = NULL;
int val;
std::ofstream filout;
filout.open("data.txt",std::ios::out|std::ios::app|std::ios::binary);
while(true){
std::cin>>val;
if(val==0)
break;
else{
add(head,val);
filout.write((char*)&head, sizeof(head));
}
}
std::ifstream filin;
filin.open("data.txt",std::ios::in|std::ios::binary);
filin.read((char*)&head, sizeof(head));
print(head);
return 0;
}
我应该对我的代码进行哪些修改以使其正确?
更新:
当我第一次尝试执行程序时,我可以轻松地插入一些值并通过输入 0 来终止程序,一切都很好。但是,当我第二次运行该程序时,我的打印函数中的 std::cout 语句中会出现 EXC_BAD_ACCESS error 声明
【问题讨论】:
-
"但我失败了" 怎么样?你得到什么错误?顺便说一句,你忘了添加 c++03、c++17 和 c++20 标签。
-
第一张图是输出,第二张是一些代码的截图...?!?
-
请勿插入图片!您可以在此处复制屏幕的输出并用“fails here with...”注释您的源代码
-
好吧,让我稍微修改一下:'D!
-
我现在明白了。尝试在程序运行之间删除文件。但这种方法是一种非常糟糕的主意。如果您需要将结构存储在文件中,请寻找序列化器和反序列化器
标签: c++ c++11 linked-list c++14 file-handling