【问题标题】:Reading a data from a file and writing it to a linked list从文件中读取数据并将其写入链表
【发布时间】:2016-11-06 12:51:09
【问题描述】:
#include<stdio.h>
struct Node{
    char *name;
    int time;
    int sec; 
    int x;
    int y;
    struct Node *next;
};
int main(){
    FILE *file;
    int index;
    struct Node *data=malloc(sizeof(struct Node));
    struct Node *tmp=data,*tmp2=data;
    int enter;

    file=fopen("data.txt","r");

    if(file==NULL){
        printf("File was not opened!\n");
        return 0;
    }

    while(!feof(file)){
        tmp=malloc(sizeof(struct Node));
        fscanf(file,"%d",&index);
        fscanf(file,"%d",&tmp->time);
        fscanf(file,"%d",&tmp->sec);
        fscanf(file,"%d",&tmp->x);
        fscanf(file,"%d",&tmp->y);
        fscanf(file,"%s",tmp->name);
        fscanf(file,"%'\0",&enter);
        tmp->next=NULL;
        tmp=tmp->next;
    }
    fclose(file);
    while(tmp2 != NULL){
        printf("file:%d\t%d\t%d\t%d\t%s\n",tmp2->timestamp,tmp2->sec,tmp2->pointx,tmp2->pointy,tmp2->name);
        tmp2=tmp2->next;
    }
    return 0;
}

需要一些帮助来从文件中读取数据并将它们写入链接列表,然后将链接列表打印到屏幕上。但是在我启动程序后它立即停止工作。文件中的数据是这样的:

  • 1 28000 41 29 50 bbb
  • 2 29000 91 19 60 立方厘米
  • 3 30000 23 77 92 ddd
  • 4 30000 37 62 65 eee
  • 5 31000 14 45 48 fff

(它们之间有标签)

我读了很多问题,但他们的答案对我没有帮助。我想我在某处遗漏了一点,但我看不到问题。是直接将数据读取到链接列表还是其他什么?感谢帮助。 //我正在查看我的代码再次感谢您的帮助**(已编辑)

【问题讨论】:

  • 这个"%'\0"和这个"%'"一模一样,按照你的说法应该怎么做?如果您阅读文档,您认为它会做什么?
  • ".. 它给出了一条错误消息.." 请永远不要让我们猜测您遇到的具体错误。
  • 顺便说一句,你还在学习,你应该阅读很多并进行实验。请注意,您需要几天的全职工作来完成这项作业。
  • 您的代码中存在编译错误。例如:代码试图访问不存在的结构中的pointx和pointy。我同意其他人将此问题作为学习机会并对其进行更多调试。通过 gdb 运行它肯定会很有趣..

标签: c linked-list text-files scanf


【解决方案1】:

name 字段是一个指针,但您从不分配它。所以

    fscanf(file,"%s",tmp->name);

undefined behavior。你真的应该是very scared。花几个小时阅读 Lattner 的博客:what every C programmer should know about undefined behavior

如果在 POSIX 系统上读取一行,您可能会使用getline(3),或者使用fgets(3)

顺便说一句,当我编译带有所有警告和调试信息的代码时(如果使用 GCC,则使用 gcc -Wall -g)我收到很多错误和警告。你应该改进你的代码,直到你没有收到任何警告。然后您应该使用调试器 (gdb) 来查找许多其他错误。您将能够逐步运行您的错误程序并查询一些变量。您应该在黑板上(或纸上)画出您认为是运行程序的process 的内存(包括堆)的模型和形状。你会发现几个错误。阅读更多关于 C dynamic memory allocationvirtual address space 的信息。

另外,使用malloc(3)时需要#include &lt;stdlib.h&gt;

请阅读您正在使用的每个函数的文档,尤其是fscanf

注意你忘了处理malloc的失败;我还建议在失败的情况下使用perror(3)。所以至少将tmp=malloc(sizeof(struct Node));替换为

tmp = malloc(sizeof(struct Node));
if (!tmp) { perror("malloc Node"); exit(EXIT_FAILURE); };

PS。我希望你不要指望我们做你的功课。您的程序有很多错误,但是通过您自己这些错误,您会学到很多东西。问别人会适得其反。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2019-06-28
    • 2011-11-06
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多