你会更好使用fgets
读取整个行到内存中,然后strtok
到tokenise行成单独的元素。
以下代码显示了执行此操作的一种方法。首先,标题和结构definintion:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct sMyPath {
char *element;
struct sMyPath *next;
} tMyPath;
然后,主要功能,首先创建一个空的列表,然后从用户获取输入(如果你想有一个强大的输入功能,看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.
};