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

对着背影说爱祢 提交于 2019-12-24 00:53:25

问题


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). However, I tested it on the directory /etc/network which has a symbolic file called run and it appeared as d? I've tried re-arranging the order of the if-statements too, but that gives an unsatisfactory output too. 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");   
            }
    }

回答1:


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



回答2:


In this line: 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:

    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.



来源:https://stackoverflow.com/questions/22394584/c-sys-stat-h-functions-s-islnk-s-isdir-and-s-isreg-behaving-oddly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!