2013-05-04 51 views
1

我想读在每一行的以下格式内置的文本文件,例如:如何使用fscanf读取一行来解析变量?

a/a1.txt 
a/b/b1.txt 
a/b/c/d/f/d1.txt 

使用fscanf来读取文件中的一行,你怎么能自动解析行成的变量其中每个元素是路径部分(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. 
} 

回答

2

你会更好使用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. 
};