1

所以我写了一个简短的 C 程序来探索我计算机上的文件以查找某个文件。我写了一个简单的函数,它接受一个目录,打开它并环顾四周:

int exploreDIR (char stringDIR[], char search[])
{    
    DIR* dir;
    struct dirent* ent;   

    if ((dir = opendir(stringDIR)) == NULL)
    {
         printf("Error: could not open directory %s\n", stringDIR);
         return 0;             
    }

    while ((ent = readdir(dir)) != NULL)
    {
        if(strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
             continue;

        if (strlen(stringDIR) + 1 + strlen(ent->d_name) > 1024)
        {
            perror("\nError: File path is too long!\n");
            continue;
        }     

        char filePath[1024];
        strcpy(filePath, stringDIR);
        strcat(filePath, "/");
        strcat(filePath, ent->d_name);

        if (strcmp(ent->d_name, search) == 0)
        {
            printf(" Found it! It's at: %s\n", filePath);
            return 1;
        }

        struct stat st; 
        if (lstat(filePath, &st) < 0)
        {
            perror("Error: lstat() failure");
            continue; 
        }

        if (st.st_mode & S_IFDIR)
        {
             DIR* tempdir;
             if ((tempdir = opendir (filePath)))
             {
                 exploreDIR(filePath, search);               
             }

         }

    }
    closedir(dir);
    return 0; 
}

但是,我不断得到输出:

Error: could not open directory /Users/Dan/Desktop/Box/Videos
Error: could not open directory /Users/Dan/Desktop/compilerHome

问题是,我不知道这些文件可能导致 opendir() 失败的原因。我没有在任何程序中打开它们。它们只是我在桌面上创建的简单文件夹。有谁知道问题可能是什么?

4

1 回答 1

2

opendir()每次调用两次closedir()。也许你的资源已经用完了。

于 2013-10-06T19:17:34.890 回答