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