linux上C语言的直接迭代

linux上C语言的直接迭代,c,dirent.h,C,Dirent.h,我试图通过一个目录,当遇到一个文本文件,我想打开它。出于某种原因,在我点击文本文件之前,我在while循环中得到了一个null条件,所以它很早就退出了,我不知道为什么 循环条件 while ((pDirent = readdir(pDir)) != NULL) { printf("*******"); printf("The filePath is: %s \n", filePath); printf("dirent is %s \n", pDirent->d_n

我试图通过一个目录,当遇到一个文本文件,我想打开它。出于某种原因,在我点击文本文件之前,我在while循环中得到了一个null条件,所以它很早就退出了,我不知道为什么

循环条件

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_名称也为空。

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

#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);
            }
            
        }
    }

建议:发布代码的所有相关部分将帮助您获得更快的响应。在这种情况下,必须有代码在目录结构中递归。@user3386109这就是我的循环所做的,但实际上现在它只找到一个txt,然后退出循环。调试器怎么说?看起来你希望readdir递归到子dir中-它确实如此not@pm100我有一个问题,你能解释一下你说的儿童导演是什么意思吗?readir做什么?我怎样才能像我想的那样度过难关?