![](/img/trans.png)
[英]S_ISDIR and S_ISREG undeclared despite including the <sys/stat.h> header
[英]C: <sys/stat.h> functions S_ISLNK, S_ISDIR and S_ISREG behaving oddly?
从中获取的代码可以很好地进行编译。 它在目录中打印文件名,并在文件名前打印一个字母: d
, f
, l
或o
取决于文件类型(其他为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_ISDIR
, S_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.