2016-01-22 87 views
1

我只想讀取子目錄和指向子目錄的鏈接。 使用下面的代碼我讀了所有的subdirs和鏈接。確定鏈接指向的目錄條目的類型

struct dirent* de; 
DIR* dir = opendir(c_str()); 
if (!dir) { /* error handling */ } 

while (NULL != (de = readdir(dir))) { 
    if (de->d_type != DT_DIR && de->d_type != DT_LNK) 
     continue; 
    // Do something with subdirectory 
} 

但是,如何檢查鏈接是否也指向子目錄呢?我不想閱讀整個鏈接目錄來執行此操作。

+0

爲了什麼目的,你既C和C++標籤呢? – usr2564301

+3

您是否在尋找readlink? http://linux.die.net/man/3/readlink – mikedu95

+2

'readlink'得到指向的東西的路徑,'stat'用於檢查它是否是一個目錄? – mindriot

回答

3

您可以使用一個名爲stat<sys/stat.h>功能:

struct dirent* de; 
struct stat s; 
DIR* dir = opendir(c_str()); 
if (!dir) { /* error handling */ } 

while (NULL != (de = readdir(dir))) { 
    if (de->d_type != DT_DIR) { 
     char filename[256]; 
     sprintf(filename, "%s/%s", c_str(), de->d_name); 
     if (stat(filename, &s) < 0) 
      continue; 
     if (!S_ISDIR(s.st_mode)) 
      continue; 
    } 
    // Do something with subdirectory 
} 
+0

@ Th.Thielemann:如果'de-> d_type'是'DT_UNKNOWN',或者你正在編譯一個系統甚至沒有在'struct dirent'中提供'd_type'字段,你仍然需要使用'stat' 。這是一個真正的問題,因爲它仍然是XFS文件系統的新功能。它需要磁盤元數據的最新格式以及尚未默認的元數據CRC。 'mkfs.xfs'的默認值是'-n ftype = 0',所以即使是新安裝的新創建的XFS文件系統也不會支持它,除非管理員手動選擇啓用該選項。 –

+0

您仍然可以利用'd_type'來避免'stat()'除了符號鏈接(可能指向一個目錄,或者可能不指向)之外的任何東西。 –

+2

'char filename [256];'然後'sprintf()'到那個緩衝區中?這是緩衝區溢出的祕訣。 –