我正在尝试浏览目录,遇到文本文件时,我想打开它。由于某种原因,我在打文本文件之前在while循环中得到了空条件,因此它早早退出了,我不确定为什么。

https://ideone.com/7iHTK1

循环条件

while ((pDirent = readdir(pDir)) != NULL)
{
    printf("*******");
    printf("The filePath is: %s \n", filePath);
    printf("dirent is %s \n", pDirent->d_name);
    if (strcmp(pDirent->d_name, ".") == 0 || strcmp(pDirent->d_name, "..") == 0)
    {
        printf("get that shit %s\n", pDirent->d_name);
        continue;
    }
    strcat(filePath, pDirent->d_name);
    printf ("[%s]\n", filePath);
    printf("Is regular? %d \n", IsRegularFile(filePath));
    printf("Is dir? %d \n", isDirectory(filePath));
    strcat(filePath, "/");
    printf("%c %c %c \n",filePath[strlen(filePath) - 4], filePath[strlen(filePath) - 3],filePath[strlen(filePath) - 2]);
    if (filePath[strlen(filePath) - 4] == 't' && filePath[strlen(filePath) - 3] == 'x' && filePath[strlen(filePath) - 2] == 't') //add check for length and .txt
    {
        printf("File is txt\n");
        break;
    }
    printf("end of loop\n");
}


被满足,然后退出。我有文件结构:

testDir(testDir1)

testDir1(testDir1-2)

testDir1-2(testFile.txt)

基本上它到达testDir1-2,然后退出循环,我的文件路径是testDir / testDir1 / testDir1-2,由于某种原因,它从未获得过testFile.txt。 pDirent-> d_name也为null。

最佳答案

您没有更新目录。您必须递归更新目录,并使用循环来迭代当前目录。

#define is_regular 0100000

    void scan (const char* directory)
    {
        DIR* pdir = opendir (directory);

        dirent *pent = NULL;



        while (pent = readdir (pdir))
        {

            if (pent->d_name[0] == '.')
                continue;


            char* fileName = (char*) malloc(strlen(directory) + strlen(pent->d_name) + 2);
            strcpy(fileName,directory);
            strcat(fileName, "/");
            strcat(fileName, pent->d_name);

            struct stat st;
            stat(fileName, &st);

            if (st.st_mode & is_regular)
            {
                //get the file, check whether a txt or not
            }
            else
            {
                scan (fileName);
            }

        }
    }

关于c - Linux上C语言的Dirent迭代,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22671997/

10-08 22:04