繁体   English   中英

使用C中的fgets和strtok读取文件并将信息保存在喜欢的列表中

[英]Reading file and save information in a liked list using fgets and strtok in C

我正在尝试读取只有一行名称用逗号分隔的文件,因此我正在使用fgets读取行,然后用strtok分隔名称,然后我想将这些名称保存在链接列表中。 我使用的是CodeBlocks,运行程序时显示以下消息:“进程终止,状态为-1073741510”

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define MAX_CHAR 200

typedef struct Names{
    char* name;
    struct Names* next;
}Names;

Names* create_list(){

    Names* aux = (Names*) malloc (sizeof(Names));
    assert(aux);
    aux->next = NULL;
    return aux;
}
void insert_name (Names* n, char* p){

    Names* aux = (Names*)malloc(sizeof(Names));
    aux->name = p;
    while(n->next!=NULL){
        n=n->next;
    }
    aux->next=n->next;
    n->next=aux;
}

void config(Names*p){

    FILE* fp = fopen( "names.txt", "r");

    if(fp == NULL){
        printf("Error opening file");
        return;
    }
    else{
        char line[MAX_CHAR],*token;

        fgets(line, MAX_CHAR, fp);
        token = strtok(line,",");
        insert_name(p,token);
        while(token != NULL);{
            token = strtok(NULL,",");
            insert_name(p,token);
        }
        fclose(fp);
    }
}

void print_list(Names* n){
    Names* l = n->next;
    while (l){
        printf("%s\n",l->name);
        l = l -> next;
    }
}

int main()
{
    Names* n;
    n = create_list();
    config(n);
    print_list(n);

    return 0;
}

您在这里遇到无限循环:

while(token != NULL);{

分号终止while的“ body”,花括号只是打开未附加到任何控件结构的代码块。 (这是合法的,并且是在C99之前确定变量范围的一种方法。)

没有分号,循环仍然是错误的:您应该仅在知道令牌不为NULL时插入:

token = strtok(line,",");

while (token != NULL) {
    insert_name(p,token);
    token = strtok(NULL,",");
}

您的代码中仍然存在错误:

  • 您的令牌是指向本地数组´line的指针. When you leave . When you leave config时, these pointers become invalid, because line将变为无效。 您应该复制字符串,而不是只存储一个指针。
  • 在程序结束时,每次调用malloc都应free调用。 在其他地方,清理您的清单。

我认为首先您需要将名称的分配修改为strcpy或memcpy,还需要使用动态分配

  aux->name = (char*) malloc(strlen(p));
  strcpy(aux->name, p);

要么

  typedef struct Names{
     char name[MAX_NAME_LEN];
     struct Names* next;
  }Names;
  //and use strcpy or memcpy in insert_name function

希望这会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM