我正在尝试在每一行中读取使用以下格式构建的文本文件,例如:
a/a1.txt
a/b/b1.txt
a/b/c/d/f/d1.txt
使用fscanf
从文件中读取一行,如何自动解析该行到*element
和*next
的变量,每个元素都是一个路径部分(a
、a1.txt
、b
、c
、d1 .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/