【问题标题】:How can I find the permissions for sub-folders in file's path in C under Linux?如何在Linux下找到C文件路径中子文件夹的权限?
【发布时间】:2011-06-01 10:58:46
【问题描述】:

我正在尝试查找文件路径中具有“其他 exec”权限的所有子文件夹。

我尝试使用strtok(path_str,"/") 来破坏路径字符串,但是当使用stat() 作为我运行的进程根目录的子目录时,我收到“不是文件或文件夹”错误。

关于如何克服此错误的任何建议?

【问题讨论】:

  • 只需将您输入的路径名记录到stat()。我敢打赌,您的字符串拆分算法有误。顺便看看dirname()函数。
  • 我们能否看到重现您症状的最小工作代码,并了解您遇到的实际errno?快速阅读表明您天真地 stat()ing 路径的各个组件名称,即标记“path/to/something”和 stat()ing “path”(ok)、“to”(ENOENT,可能)和“某物”(可能是 ENOENT)。然而,没有代码,一切都是猜测。
  • pilcrow,你是对的。这是我的问题,如果我从执行该过程的目录中统计()“to”,则找不到它,从而导致错误。那么,我还能遇到这种情况吗?

标签: c linux path stat


【解决方案1】:

我已经解决了,

首先我从路径中删除了第一个“/”(我不完全理解为什么会这样) 比我将代码更改为 do-while 以在最后访问文件。 所以这里是整个代码:

do{
    int retval;
    if (temp_ptr != NULL) //before the first strrchr its null
        *temp_ptr = 0;
    if (*temp_path)
       retval = stat(temp_path, statbuf);
    else
        retval = stat("/", statbuf);
    if (retval < 0){
        perror("stat");
    }
     printf("%s\n",temp_path);

    if(S_ISDIR(statbuf->st_mode)){
        printf("\tis a directory\n");
    }else if(S_ISREG(statbuf->st_mode)){
        printf("\tis a regular file\n");
    }


}   while ((temp_ptr = strrchr(temp_path, '/')));

感谢咖啡馆和所有人的帮助。

【讨论】:

    【解决方案2】:

    如果路径是"long/path/to/the/file.txt",那么您需要在"long""long/path""long/path/to""long/path/to/the" 上调用stat()。如果您不在乎检查这些的顺序,最简单的方法可能是重复使用strrchr()

    char *s;
    
    while (s = strrchr(path, '/'))
    {
        *s = 0;
        if (strlen(path) > 0)
            stat(path, &statbuf);
        else
            stat("/", &statbuf);
    
        /* Do something with statbuf */
    }
    

    (特殊情况是针对以/开头的路径,检查根目录本身)。

    【讨论】:

    • @caf: 你写if (strlen(path)&gt;0) 真丢脸! if (*path) 更简单,避免了整个不必要的字符串遍历。
    • @R.: 是的,但我的 gcc 版本自己执行转换,即使在 -O0 上也是如此。
    • 不错。虽然我有点惊讶它在-O0 上做到了。当函数调用在调试时完全消失时,这可能会让很多新手感到不安......
    • @R.:这有点令人惊讶。 -fno-builtin 确实禁用它。
    • @caf: 谢谢,我试过了,它给了我以下输出: /filepath/layer2/example.txt stat: 没有这样的文件或目录 /filepath/layer2 stat: 没有这样的文件或directory /filepath 是一个目录所以,它只给出了我的进程目录中的目录。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 2010-12-25
    • 2017-07-17
    • 1970-01-01
    相关资源
    最近更新 更多