Вопрос

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");   
            }
    }
Это было полезно?

Решение 2

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

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top