【问题标题】:C: <sys/stat.h> functions S_ISLNK, S_ISDIR and S_ISREG behaving oddly?C: <sys/stat.h> 函数 S_ISLNK、S_ISDIR 和 S_ISREG 行为异常?
【发布时间】:2014-04-19 03:06:26
【问题描述】:

从编译中获取的代码很好。它在一个目录中打印文件名,前面有一个字母选项:dflo,具体取决于它们的文件类型(o 用于其他)。但是,我在目录/etc/network 上对其进行了测试,该目录有一个名为run 的符号文件,它显示为d?我也尝试过重新安排if-statements 的顺序,但这也给出了不令人满意的输出。是不是我用错了?

while ((ent = readdir (dp)) != NULL) {
    lstat(ent->d_name, &st);
    if (col){
            if(S_ISDIR(st.st_mode)){
                    printf("d\t");
                    }
           else if (S_ISREG(st.st_mode)){
                    printf("f\t");
                    }
            else if (S_ISLNK(st.st_mode)){
                    printf("l\t");
            }
            else {   
                     printf("o\t");   
            }
    }

【问题讨论】:

    标签: c file-type ls


    【解决方案1】:

    在这一行:lstat(ent-&gt;d_name, &amp;st);dp-&gt;d_name 只包含文件名,你需要将文件的完整路径传递给lstat(),如下所示:

        char full_path[512] = "DIR_PATH"; //make sure there is enough space to hold the path.
        strcat(full_path, ent->d_name);
        int col = lstat(full_path, &st);
    

    顺便说一句,S_ISDIRS_ISLNK 等是 POSIX 宏,而不是函数。

    【讨论】:

      【解决方案2】:

      这可以作为替代解决方案:

      if(col){
      
                  if(ent->d_type == DT_DIR)
                      printf("d ");
                  else if(ent->d_type == DT_LNK)
                      printf("l ");
                  else if(ent->d_type == DT_REG)
                      printf("f ");
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多