0

我试图测试我的程序,看看它是否会获取 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;
}

}
4

4 回答 4

1

还,

您正在尝试从此处读取文件:

    FILE *pFile;
    pFile = fopen("path.txt", "w");
    char inputstr[1024];
    tMyPath *curr, *first = NULL, *last = NULL;

但是,我看到您正在使用“w”(写入)选项从文件中读取。如果你使用过会更合适

pFile = fopen("path.txt", "r");

于 2013-05-04T20:39:06.327 回答
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;
}

更重要的是,fgets一次读取一行,所以这段代码只读取第一行。

我想你想要fgetc

于 2013-05-04T20:34:03.330 回答
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 告诉你的那样。

于 2013-05-04T20:40:48.087 回答
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;
}
于 2013-05-04T21:10:43.647 回答