簡體   English   中英

如何使用fscanf讀取要解析為變量的行?

[英]How to use fscanf to read a line to parse into variables?

我正在嘗試讀取每行以以下格式構建的文本文件,例如:

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;

然后,主函數首先創建一個空列表,然后從用戶那里獲取輸入(如果您想要一個健壯的輸入函數,請參見此處 ,以下內容僅是出於演示目的的簡化版本):

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,但是您始終可以某處找到不錯的實現 )。 然后,我們打印出鏈接列表以顯示它已正確加載,然后清除並退出:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM