2013-05-04 27 views
0

我是否正确地获取包含字符串路径的文本文件,并获得链接列表的正确实现? 所以我可以稍后创建一个搜索功能,以查看文件是否存在。使用字符串路径将链接链接到文件,它是正确的实现吗?

文本文件:path.txt

a/a1.txt 
a/a2.txt 
a/b/b3.txt 
a/b/b4.txt 
a/c/c4.txt 
a/c/c5.txt 
a/c/d/d6.txt 
a/c/d/g 
a/c/d/h 
a/c/e/i/i7.txt 
a/c/f/j/k/k8.txt 

代码

#include <string.h> 
#include <stdio.h> 
#include <stdlib.h> 

typedef struct sMyPath{ 
     char *element; 
     struct sMyPath *next; 
} tMyPath; 


int main(void) 
{ 
     FILE *pFile; 
     pFile = fopen("path.txt", "r"); 
     char inputstr[1024]; 
     tMyPath *curr, *first = NULL, *last = NULL; 

//get the text file, and put it into a string inputstr 

    if (pFile != NULL) 
    { 
      while(!feof(pFile)) 
      { 
        fgets(inputstr, sizeof(inputstr), pFile); 
      } 
    fclose(pFile); 
    } 
    else 
    { 
      printf("Could not open the file.\n"); 
    } 

使用令牌来获得每一块串的 //单独的目录和文本文件,把它变成一个链接//列表

char *token = strtok(inputstr, "/"); 
    while (token != NULL) 
    { 
    if(last == NULL){ 
      //creating node for directory 
      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, "/"); 
     } 

return 0; 
} 
+0

我想尝试http://codereview.stackexchange.com/进行代码评论 – rickythefox 2013-05-04 22:25:25

回答

2

我假设你需要我们来验证这个程序,文件存在于给定列表中。这看起来不错,我除了下面的原因,

1),你必须将包含类似目录的这么多的重复条目的链接列表,

a, b, c, d.... 

作为分隔符是“/”。不确定这是否是预期的。 将分隔符设为'\ n'会更好地达到目的,恕我直言......

2)文件的大小是固定的。最好在文件上做一个统计,然后分配内存来保存文件数据

3)免费由strdup返回的上载内存。