【问题标题】:How to use fscanf to read a line to parse into variables?如何使用 fscanf 读取一行来解析成变量?
【发布时间】:2013-05-04 07:09:48
【问题描述】:

我正在尝试在每一行中读取使用以下格式构建的文本文件,例如:

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

使用fscanf从文件中读取一行,如何自动将行解析为*element*next的变量,每个元素都是一个路径部分(aa1.txt,@ 987654327@、cd1.txt 等)。

我的结构如下:

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

【问题讨论】:

    标签: c parsing file-io scanf


    【解决方案1】:

    最好使用fgets 将整行读入内存,然后使用strtok 将行标记为单个元素。

    以下代码显示了一种方法。一、标题和结构定义:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef struct sMyPath {
        char *element;
        struct sMyPath *next;
    } tMyPath;
    

    然后是 main 函数,最初创建一个空列表,然后从用户那里获取输入(如果您想要一个健壮的输入函数,请参阅 here,以下是该函数的简化版本,仅用于演示目的):

    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';
    

    然后是提取所有标记并将它们添加到链表的代码。

        // 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, "/");
        }
    

    (请记住,strdup 不是标准 C,但您总能在某处找到 a decent implementation)。然后我们打印出链表以显示它已正确加载,然后清理并退出:

        // 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;
    }
    

    示例运行如下:

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

    我还应该提到,虽然 C++ 允许您从结构中删除 struct 关键字,但 C 不允许。你的定义应该是:

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

    【讨论】:

      猜你喜欢
      • 2011-07-09
      • 1970-01-01
      • 2018-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 2017-12-05
      • 1970-01-01
      相关资源
      最近更新 更多