0

我的程序似乎没有正确打开文本文件。我有一个 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");
        }

//使用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, "/");
}

//向用户询问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;
}
4

2 回答 2

1

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

于 2013-05-04T22:57:27.677 回答
1

我了解两个可能的要求/实现。

1)通过您的实现,每个链接节点将只包含文件名和目录名,而不是 PATH-NAME。如果您需要存储整个路径名,请使用'\n'作为分隔符。

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 )

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

于 2013-05-04T23:33:41.010 回答