C: <sys/stat.h> functions S_ISLNK, S_ISDIR and S_ISREG behaving oddly?
10,001
Solution 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 ");
}
Solution 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.
Author by
COOLBEANS
Updated on June 14, 2022Comments
-
COOLBEANS about 2 years
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
, oro
depending on their file type (o
for other). However, I tested it on the directory/etc/network
which has a symbolic file calledrun
and it appeared asd
? I've tried re-arranging the order of theif-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"); } }