[英]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.