【问题标题】:Seemingly random opendir() failure C看似随机的 opendir() 失败 C
【发布时间】:2013-10-06 19:10:45
【问题描述】:

所以我编写了一个简短的 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() 失败。我没有在任何程序中打开它们。它们只是我在桌面上创建的简单文件夹。有谁知道问题可能是什么?

【问题讨论】:

  • chmod r+x /Users/Dan/Desktop/Box/Videos 并重试。
  • 只需通过sudo执行
  • 检查errno 告诉你什么?
  • 您为每个 closedir() 调用了两次 opendir()。也许你的资源已经用完了。
  • @ZagorulkinDmitry:坏主意。不要将sudo 或一般的root 访问权用于任何不必要的事情。在这种情况下,它无论如何也无济于事。

标签: c opendir


【解决方案1】:

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

【讨论】:

  • 啊,这就是问题所在!我不敢相信我忘记了第二个 opendir()。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-05
  • 2016-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-05
  • 1970-01-01
相关资源
最近更新 更多