简体   繁体   中英

How to fscanf a file into a linkedlist?

so i have a file that consist of integers. And i would like to use fscanf to read the file's integers into a linkedlist. But during the compile time, the function just wait there for an input(as if there is a scanf somewhere in the function). Please Help me :(

Code

struct Node{
int data;
struct Node *next;
};

typedef struct Node Node;



void fillListFromFile(Node **head)
{
    FILE *f;
    if((f=fopen("/home/fileOints001.txt","r"))==NULL)
        printf("You cannot open");
    Node *newNode = malloc(sizeof(Node));
    while(fscanf(f, "%d", &(newNode->data)))
    {
    newNode->next = *head;
    *head = newNode;
    Node *newNode = malloc(sizeof(Node));

    }

}



fillListFromFile(&head); // in the main

Your loop only ends if it fails to convert the input (ie fscanf() will return 0 here). But you do not check for EOF . Thus, you spin your wheels trying to read over and over. Something like:

int rc;

/* ... */

while ((rc = fscanf(...)) && rc != EOF) {
    /* ... */
}

This way you check for the end of file condition, and terminate the loop when you hit it.

You need some error checking to make sure that your file parses correctly and the like.

Also, it may be a good idea not to allocate a node before its data has been successfully read.

typedef struct Node {
    int data;
    struct Node *next;
} Node;

Node* fillListFromFile()
{
    FILE *f;
    if(!(f = fopen("/home/fileOints001.txt","r"))) {
        perror("/home/fileOints001.txt");
        abort();
    }

    Node *head = NULL, **tail = &head, *node;
    int n;
    while(1 == fscanf(f, "%d", &n)) {
        // allocate a new node
        node = malloc(sizeof(Node));
        if(!node) {
            fprintf(stderr, "failed to allocate memory");
            abort();
        }

        // and append it to the list
        node->data = n;
        node->next = NULL;
        *tail = node;
        tail = &node->next;
    }
    if(!feof(f)) {
            fprintf(stderr, "failed to parse the file");
            abort();
    }

    return head;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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