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