简体   繁体   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?

The code this is taken from compiles fine. 从中获取的代码可以很好地进行编译。 It prints file names in a directory with the option of a letter in front of it: either a d , f , l , or o depending on their file type ( o for other). 它在目录中打印文件名,并在文件名前打印一个字母: dflo取决于文件类型(其他为o ))。 However, I tested it on the directory /etc/network which has a symbolic file called run and it appeared as d ? 但是,我在目录/etc/network上对其进行了测试,该目录有一个名为run的符号文件,显示为d ?。 I've tried re-arranging the order of the if-statements too, but that gives an unsatisfactory output too. 我也尝试过重新安排if-statements的顺序,但这也给出了不令人满意的输出。 Am I using it incorrectly? 我使用不正确吗?

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

In this line: lstat(ent->d_name, &st); 在这一行: lstat(ent->d_name, &st); , dp->d_name contains only the name of the file, you need to pass the full path of the file to lstat() like this: 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_ISDIR , S_ISLNK etc are POSIX macros, not functions. BTW, S_ISDIRS_ISLNK等是POSIX宏,而不是函数。

This might work as an alternative solution: 这可以作为替代解决方案:

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