我试图测试我的程序,看它是否会得到path.txt文件,并输出第一行分隔的文件和目录字符串,但是当我运行程序时什么都没有出现。它似乎经历了无限循环。怎么能解决这个问题?
文本文件: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 MyPath{
char *element;
struct MyPath *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");
}
//using tokens to get each piece of the string
//seperate directories and text files
char *token = strtok(inputstr, "/");
while (token != NULL)
{
//print
printf("%s\n", token);
//basecase
token = strtok(NULL, "/");
return 0;
}
}
答案 0 :(得分:1)
此外,
您正试图在此处阅读文件:
FILE *pFile;
pFile = fopen("path.txt", "w");
char inputstr[1024];
tMyPath *curr, *first = NULL, *last = NULL;
但是,我发现您使用“w”(写入)选项从文件中读取。如果你使用过
会更合适 pFile = fopen("path.txt", "r");
答案 1 :(得分:0)
转动
char *token = strtok(inputstr, "/");
while (token != NULL)
{
//print
printf("%s\n", token);
//basecase
token = strtok(NULL, "/");
return 0; //HERE!
}
}
进入
char *token = strtok(inputstr, "/");
while (token != NULL)
{
//print
printf("%s\n", token);
//basecase
token = strtok(NULL, "/");
}
return 0;
}
More importantly, fgets
reads one line in at a time, so this code is only reading the first line.
答案 2 :(得分:0)
问题在于您的fopen,您使用的是“w”模式:
w Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
将其修改为“r”,它应该与返回一起使用; @frickskit告诉你。
答案 3 :(得分:0)
像这样修复
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct MyPath{
char *element;
struct MyPath *next;
} tMyPath;
int main(void){
FILE *pFile;
char inputstr[1024];
tMyPath *curr, *first = NULL, *last = NULL;
pFile = fopen("path.txt", "r");
if (pFile != NULL){
while(!feof(pFile)){
fgets(inputstr, sizeof(inputstr), pFile);
{
char *token = strtok(inputstr, "/");
while (token != NULL){
printf("%s\n", token);
token = strtok(NULL, "/");
}
}
}
fclose(pFile);
} else{
printf("Could not open the file.\n");
}
return 0;
}