如何使用fscanf读取要解析为变量的行?
我试图在每一行中读取以下格式的文本文件,例如:如何使用fscanf读取要解析为变量的行?,c,parsing,file-io,scanf,C,Parsing,File Io,Scanf,我试图在每一行中读取以下格式的文本文件,例如: 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; // Po
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;
然后使用代码提取所有令牌并将它们添加到链接列表中
// 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++允许你从结构中删除<代码>结构> /COD>关键字,而C则不这样做。你的定义应该是:
struct MyPath {
char *element; // Pointer to the string of one part.
struct MyPath *next; // Pointer to the next part - NULL if none.
};
struct MyPath {
char *element; // Pointer to the string of one part.
struct MyPath *next; // Pointer to the next part - NULL if none.
};