【问题标题】:using a string path to link list to files, is it the proper implementation?使用字符串路径将列表链接到文件,这是正确的实现吗?
【发布时间】:2013-05-04 21:41:02
【问题描述】:

我是否正确获取了包含字符串路径的文本文件,并正确实现了链接列表? 所以我以后可以创建一个搜索功能,看看文件是否存在。

文本文件: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");
    }

//使用token获取字符串的每一段 //单独的目录和文本文件,放到一个链接列表中

    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;
}

【问题讨论】:

标签: c tree linked-list


【解决方案1】:

我假设您需要我们验证这个程序,该程序会在给定列表中查找文件是否存在。这对我来说看起来不错,除了以下原因,

1) 您拥有的链接列表将包含许多重复的目录条目,例如,

a, b, c, d....

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

2) 文件大小是固定的。最好对文件进行统计并分配内存来保存文件数据

3) 释放由 strdup 返回的内存。

【讨论】:

    猜你喜欢
    • 2015-06-02
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多