我的程序似乎没有正确打开文本文件。 我有一个 path.txt,它是我创建的所有文件夹和文本文件路径的字符串表示形式。但是,当运行该程序时,它不会输出用户要求的文本文件的行。
输出
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;
}
最佳答案
我了解两种可能的要求/实现。
1) 通过您的实现,每个链接节点将仅包含文件名和目录名以及NOT THE 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 )
如果您的要求更明确,我可以帮助您提供更好的解决方案..
关于c - 我的搜索链表实现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16379671/