c - 如何使用fscanf读取一行解析成变量?

标签 c parsing file-io scanf

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

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

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

我的结构如下:

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

最佳答案

最好使用 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.
};

关于c - 如何使用fscanf读取一行解析成变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16371598/

相关文章:

arrays - C:错误分配并将 2D 字符数组传递给函数后

c# - 使用 C# 从 html 中删除自定义 xml 标签

python - 在 Python 中执行 get 请求

Java - 将 jar 中的 dll 文件写入硬盘?

c - 快速读取大于c中内存的文件

java - 将 javafx.scene.image.Image 写入文件?

c - 打开 MPI - mpirun 在简单程序上因错误而退出

c - 如何在c中的Windows 8.1系统驱动器上创建文件?

c++ - WH_KEYBOARD 和 WH_KEYBOARD_LL 之间的区别?

c - 读取简单数据声明并响应分配给该变量的内存量的程序