繁体   English   中英

C: <sys/stat.h> 函数S_ISLNK,S_ISDIR和S_ISREG表现奇怪?

[英]C: <sys/stat.h> functions S_ISLNK, S_ISDIR and S_ISREG behaving oddly?

从中获取的代码可以很好地进行编译。 它在目录中打印文件名,并在文件名前打印一个字母: 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");   
            }
    }

在这一行: lstat(ent->d_name, &st); dp->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);

BTW, S_ISDIRS_ISLNK等是POSIX宏,而不是函数。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM