简体   繁体   English

从文件读取并将格式化的行输入到链接列表。 C

[英]Read from a file and input the formatted line to linked list. C

I'm trying to read from a file, line by line, a formatted string and storing it in a linked list. 我正在尝试逐行读取文件,格式化的字符串并将其存储在链接列表中。

My typedef: 我的typedef:

typedef struct s_deck {
    char name[16];
    int atk;
    int def;
    int cost;
    struct s_deck* next;
} card;

Example of a file I'm reading from: 我正在从中读取文件的示例:

Line 1: Name 4 4 5
Line 2: Name2 5 5 5

My function I'm trying to implement to do such a thing... 我正在尝试实现此功能的功能...

card *LoadDeck() {
    FILE* file = fopen("text", "r");
    if(file == NULL) {
        printf("unable to open file...\n");
    }
    char line[16];
    card* start = NULL;
    card* newest = NULL;
    card* previous = NULL;

    fgets(line, 15, file);
    card* newCard = malloc(sizeof(card));
    sscanf(line, "%s %d %d %d\n", newCard->name, &newCard->atk,
                &newCard->def, &newCard->cost);
    printf("Added:%s Attack:%d Defense:%d Cost:%d\n", newCard->name,    newCard->atk,
                newCard->def, newCard->cost);

    if (start == NULL) {
        start = LoadDeck(NULL);
        newest = start;
    } 
    else {
        newest = LoadDeck(newest);
    }

    if (previous != NULL) {
        previous->next = newCard;
    }
    fclose(file);
    return newCard;
}

So my issue I'm having is that it is an infinite loop where it reads the first line and the first line only. 所以我遇到的问题是,这是一个无限循环,其中它仅读取第一行和第一行。 The printf I have is to see what its doing and... well its reading the line correctly but it just keeps doing it and never stops. 我所拥有的printf就是看它在做什么,以及……正确地阅读该行,但是它一直在做,并且永不停止。

I don't know if its creating a linked list properly yet. 我不知道它是否正确创建了链表。 I haven't gotten that far. 我还没走那么远。 I think I implemented it right but its so hard going off books only. 我认为我实施得很对,但是很难做到这点。 I tried to find some questions here but their file they are reading from is much more complex than mine so I figured there should be a simpler way. 我试图在这里找到一些问题,但是他们正在读取的文件比我的要复杂得多,所以我认为应该有一个更简单的方法。

Well, i know maybe i should put this in comment but sorry i don't have enough reputation to do it. 好吧,我知道也许我应该对此发表评论,但是对不起,我没有足够的声誉来做到这一点。 Anyway i think your program loops endlessly because your start variable is always NULL, first call to the function is will lead to function to call itself after finding that start == NULL is true, the subsequent calls will always lead to an endless recursion because start is always NULL. 无论如何,我认为您的程序会无休止地循环,因为您的起始变量始终为NULL,在发现start == NULL为true后,对函数的首次调用将导致函数自行调用,后续调用将始终导致无限递归,因为start始终为NULL。 these lines you wrote is the black hole : 您写的这些行是黑洞

   if (start == NULL) {
    start = LoadDeck(NULL);
    newest = start; } 

It doesn't assign anything to start variable, it just causes the endless recursion. 它没有为启动变量分配任何内容,而只是导致无休止的递归。

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

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