簡體   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