我的搜索链表实现中的错误

时间:2013-05-04 22:50:24

标签: c file search linked-list

我的程序似乎没有正确打开文本文件。 我有一个path.txt,它是我创建的文件夹和文本文件的所有路径的字符串表示。但是,在运行程序时,它不会输出用户要求的文本文件的LINES。

输出

enter text file
warning: this program uses gets(), which is unsafe.
a1.txt

IT应该有输出

This is a1

a1.txt的文字:

This is a1

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

//向用户询问txt文件

char pathU[20];
printf("enter text file\n");
gets(pathU);

//检查文本文件是否存在,如果是输出文本文件,则说不是

   while(first != NULL)
    {
            if(first -> element == pathU)
            {
                    FILE *nFile;
                    char texxt[300];
                    nFile = fopen(pathU, "r");
                    while (!feof(nFile))
                    {
                            fgets(texxt, 300, nFile);
                            printf("%s", texxt);
                    }

            }

            else if(first == NULL)
            {
                    printf("invalid file name\n");
            }

            else
            {
            first = first -> next;
            }

}
return 0;
}

2 个答案:

答案 0 :(得分:1)

问题似乎在字符串比较中:first -> element == pathU。在这里,您要比较指针,而不是字符串的字符。请改为使用strcmpif (strcmp(first -> element, pathU) == 0) ...

答案 1 :(得分:1)

我理解两种可能的要求/实施。

1)通过实施,每个链接节点将只包含文件名和目录名以及 NOT THE PATH-NAME 。如果您需要存储整个路径名,请使用&#39; \ n&#39; 作为分隔符。

char *token = strtok(inputstr, "\n");

token = strtok(NULL, "\n");

这假设,当您的输入为 a / a1.txt 时,您当前的目录包含 a 目录,而该目录又包含 a1文件。 TXT

2)否则,您现有的代码希望 a1.txt 位于当前目录中,但它与输入文件内容相矛盾。


无论哪种方式,下面的代码都是罪魁祸首,

if(first -> element == pathU)

比较指针而不是字符串。将其替换为,

 if( strcmp( first -> element, pathU ) == 0 )

如果您的要求更加明确,我可以帮助您提供更好的解决方案。