0

我正在尝试浏览一个目录,当遇到一个文本文件时,我想打开它。出于某种原因,在我点击文本文件之前,我在 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");
}

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

测试目录(测试目录1)

测试目录1(测试目录1-2)

testDir1-2(testFile.txt)

基本上它到达 testDir1-2 然后退出循环,我的文件路径是 testDir/testDir1/testDir1-2 并且由于某种原因它永远不会得到 testFile.txt。pDirent->d_name 也为空。

4

1 回答 1

1

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

#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);
            }
            
        }
    }
于 2014-07-31T12:29:38.350 回答