1

I'm trying to read a text file built with the following format in every line, for example:

a/a1.txt
a/b/b1.txt
a/b/c/d/f/d1.txt

Using fscanf to read a line from file, how can you automatically parse the line into the variables of *element and *next, with each element being a path section (a, a1.txt, b, c, d1.txt and so on).

My structure is as follows:

struct MyPath {
    char *element;  // Pointer to the string of one part.
    MyPath *next;   // Pointer to the next part - NULL if none.
}
4

1 回答 1

2

You would be better off using fgets to read the entire line into memory, then strtok to tokenise the line into individual elements.

The following code shows one way to do this. First, the headers and structure definintion:

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

typedef struct sMyPath {
    char *element;
    struct sMyPath *next;
} tMyPath;

Then, the main function, initially creating an empty list, then getting input from user (if you want a robust input function, see here, what follows below is a cut down version of that for demonstrative purposes only):

int main(void) {
    char *token;
    tMyPath *curr, *first = NULL, *last = NULL;
    char inputStr[1024];

    // Get a string from the user (removing newline at end).

    printf ("Enter your string: ");
    fgets (inputStr, sizeof (inputStr), stdin);
    if (strlen (inputStr) > 0)
        if (inputStr[strlen (inputStr) - 1] == '\n')
            inputStr[strlen (inputStr) - 1] = '\0';

Then the code to extract all tokens and add them to a linked list.

    // Collect all tokens into list.

    token = strtok (inputStr, "/");
    while (token != NULL) {
        if (last == NULL) {
            first = last = malloc (sizeof (*first));
            first->element = strdup (token);
            first->next = NULL;
        } else {
            last->next = malloc (sizeof (*last));
            last = last->next;
            last->element = strdup (token);
            last->next = NULL;
        }
        token = strtok (NULL, "/");
    }

(keeping in mind that strdup is not standard C but you can always find a decent implementation somewhere). Then we print out the linked list to show it was loaded properly, followed by cleanup and exit:

    // Output list.

    for (curr = first; curr != NULL; curr = curr->next)
        printf ("[%s]\n", curr->element);

    // Delete list and exit.

    while (first != NULL) {
        curr = first;
        first = first->next;
        free (curr->element);
        free (curr);
    }

    return 0;
}

A sample run follows:

Enter your string: path/to/your/file.txt
[path]
[to]
[your]
[file.txt]

I should mention also that, while C++ allows you to leave off the struct keyword from structures, C does not. Your definition should be:

struct MyPath {
    char *element;         // Pointer to the string of one part.
    struct MyPath *next;   // Pointer to the next part - NULL if none.
};
于 2013-05-04T07:12:34.740 回答