简体   繁体   English

从C中的文件读取时出现无限循环

[英]Infinite loop when reading from file in C

Sorry this is a bit lengthy, but I've been stuck for hours now on this pesky bug from my code, and I'm really desperate. 抱歉,这有点冗长,但是由于代码中的这个令人讨厌的错误,我已经呆了几个小时了,我真的很绝望。

I'm writing a basic Rolodex program. 我正在写一个基本的Rolodex程序。 The Rolodex is a linked list, each node of which stores a person's first name, last name, and phone number (all as strings). Rolodex是一个链接列表,其每个节点都存储一个人的名字,姓氏和电话号码(全部为字符串)。 The initial contents of the Rolodex are read from a file that the user specifies, for example: Rolodex的初始内容是从用户指定的文件中读取的,例如:

bash $ ./rolodex bobsRolodex bash $ ./rolodex bobs

This rolodex would use the file "bobsRolodex." 该rolodex将使用文件“ bobsRolodex”。 If the user doesn't specify a file, it defaults to "myRolodex." 如果用户未指定文件,则默认为“ myRolodex”。 The content of each file, if there is any, is added to the linked list at the start of the program. 每个文件的内容(如果有)将在程序开始时添加到链接列表中。 Then the user is asked to either input a new contact, print the list, or quit. 然后,要求用户输入新联系人,打印列表或退出。 When the user quits, the linked list updates the file by overwriting the previous content of the file, always following the same format, which is, on consecutive lines: 当用户退出时,链接列表通过覆盖文件的先前内容来更新文件,该文件始终遵循相同的格式,即连续两行:

first last phone 倒数第一

The problem I'm having is that if there is content in the file I'm specifying, reading from the file and trying to insert the content into the linked list results in an infinite loop. 我遇到的问题是,如果我指定的文件中有内容,则从文件中读取内容并尝试将内容插入到链表中会导致无限循环。 Here is the code; 这是代码; I put a comment at the function that's giving me the problem: 我在给我这个问题的函数上加了一条评论:

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<stdbool.h>

struct Rolodex
{
    char first[40];
    char last[40];
    char phone[40];
    struct Rolodex *next;
};

typedef struct Rolodex r_struct;
r_struct *head = NULL;

void add_card_to_rolodex(r_struct* card)
{
    if(head == NULL)
    {
        card -> next = NULL;
        head = card;
    }
    else
    {
        card -> next = head;
        head = card;
    }
}

void open_and_read_from_file(char* fileName) //PROBLEM IS HERE!!!
{
    FILE* ifp = fopen(fileName, "r");
    if(ifp) //if file exists
    {
        r_struct* card = malloc(sizeof(r_struct));
        card->next = NULL;
        while(fscanf(ifp, "%s %s %s\n", card->first, card->last, card->phone) == 3)
        {
            add_card_to_rolodex(card);
        }
        fclose(ifp);
    }
}

void write_to_file(char* fileName)
{
    FILE* ofp = fopen(fileName, "w");
    r_struct* temp = head;
    while(temp != NULL)
    {
        fprintf(ofp, "%s %s %s\n", temp->first, temp->last, temp->phone);
        temp = temp->next;
    }
    fclose(ofp);
}

void print_rolodex(bool terminal)
{
    int count = 0;
    r_struct *temp = head;
    while(temp != NULL)
    {
        if(terminal)
        {
            printf("%d ", count);
            count++;
        }
        printf("%s %s %s\n", temp->first, temp->last, temp->phone);
        temp = temp->next;
    }
}

char read_command(char* fileName)
{
    char command;
    printf("%s Command: ", fileName);
    scanf("%c", &command);
    getchar();
    return command;
}

void evaluate_command(char command)
{
    if(toupper(command) == 'I') //insert new card
    {
        r_struct *card = malloc(sizeof(r_struct));
        card -> next = NULL;

        printf("Enter card: first-name last-name phone:\n");
        scanf("%s %s %s", card->first, card->last, card->phone);
        getchar();

        add_card_to_rolodex(card);
    }
    else if(toupper(command) == 'P') //print all cards
    {
        bool terminal = true;
        print_rolodex(terminal);
    }
}

void deallocate_memory()
{
    r_struct* temp = head->next;
    if(head != NULL)
    {
        while(temp != NULL)
        {
            free(head);
            head = temp;
            temp = temp->next;
        }
    }
}

int main(int argc, char *argv[])
{
    char *fileName = argv[1];
    char command;

    if(fileName == NULL)
        fileName = "myRolodex";

    open_and_read_from_file(fileName); //PROBLEM IS HERE

    while(command != 'Q')
    {
        command = read_command(fileName);
        evaluate_command(command);
    }

    write_to_file(fileName);
    deallocate_memory();
    return 0;
}

Essentially, you need to rearrange things so 本质上,您需要重新安排事情,以便

r_struct* card = malloc(sizeof(r_struct));

happens for each card you're adding to the rolodex. 您添加到rolodex的每张卡都会发生这种情况。 Currently you're overwriting the same block of memory as you're only making one call to malloc . 当前,您覆盖的内存块与仅调用malloc覆盖相同。

Alternatively take a deep copy of the structure in add_card_to_rolodex . 或者,在add_card_to_rolodexadd_card_to_rolodex该结构的深层副本。

Don't forget to clean up the memory though with calls to free when you want to destroy your linked list. 当您要销毁链表时,请不要忘了通过调用free来清理内存。

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

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