2016-02-05 48 views
1

所以我有一個項目,我需要構建一個小的簡單文本shell,可以運行,編輯和讀取目錄中的文件。我有一個小的原型應該可以工作,除了編譯時,我收到了有關在dirent.h頭文件中使用的struct dirent中找不到d_type的錯誤。struct dirent在頭文件中沒有de_type

d = opendir("."); 
c = 0; 
while ((de = readdir(d))){ 
    if ((de->de_type) & DT_DIR) 
    printf(" (%d Directory: %s) \n", c++, de->de_name); 
} 

變量「德」是類型結構的dirent *,並正在檢查它的類型,我得到的錯誤:「結構的dirent」沒有名爲「de_type」

這裏成員就是我真的難倒和困惑:我已經在兩個窗口(使用dev C++)和Ubuntu(使用gcc)上編譯了這段代碼。我收到兩個操作系統的相同的錯誤,當我檢查使用的庫,這是正常的GNU C庫,我相信,有一個變量有名爲d_type:

https://www.gnu.org/software/libc/manual/html_node/Directory-Entries.html

我發現了其他的引用到一個dirent.h文件,這並不是因爲一個庫位於不同的庫中,並且如果是這樣的話,我如何加載該庫以便編譯代碼?

對不起,很長的文章,非常感謝所有誰回答!

+0

您使用的是什麼文件系統類型? – e0k

+0

好的,所以現在這個問題根本沒有意義,因爲標題中說'd_type'和其他地方都有'de_type'。 – user3386109

回答

5

man readdir(3)

The only fields in the dirent structure that are mandated by POSIX.1 are: d_name[], of unspecified size, with at most NAME_MAX characters preceding the terminating null byte; and (as an XSI extension) d_ino. The other fields are unstandardized, and not present on all systems; see NOTES below for some further details.

然後繼續

Only the fields d_name and d_ino are specified in POSIX.1-2001. The remaining fields are available on many, but not all systems. Under glibc, programs can check for the availability of the fields not defined in POSIX.1 by testing whether the macros _DIRENT_HAVE_D_NAMLEN, _DIRENT_HAVE_D_RECLEN, _DIRENT_HAVE_D_OFF, or _DIRENT_HAVE_D_TYPE are defined.

Other than Linux, the d_type field is available mainly only on BSD systems. This field makes it possible to avoid the expense of calling lstat(2) if further actions depend on the type of the file. If the _BSD_SOURCE feature test macro is defined, then glibc defines the following macro constants for the value returned in d_type:

所以我建議只是繼續使用stat()檢查項的類型。 (或者lstat()不遵循符號鏈接。)struct stat包含字段st_mode,可以使用POSIX宏S_ISDIR(m)來檢查它是否是目錄。


附錄:見@R ..的評論下方this answer。總結:

  1. 使用正確的東西。將-D_FILE_OFFSET_BITS=64添加到您的編譯器標誌並使用64位文件偏移進行構建。
  2. 檢查您是否有d_type與預處理器宏_DIRENT_HAVE_D_TYPE。如果是這樣,請使用d_type。從目錄表中獲取所需的信息(如果可用)將比尋求讀取文件的所有inode的&更高效。
  3. 作爲回退措施,(如上所述)使用stat來讀取inode,並使用S_ISDIR()宏(或類似檢查)檢查st_mode
+1

你錯過了一個細節 - 缺少OP'd_type'的原因是它在'dirent'的遺留32位''off_t'版本中缺失,你應該永遠不會使用**。用'-D_FILE_OFFSET_BITS = 64'構建,一切都會好的。 –

+0

@R ..爲了兼容性,最好是「統計」條目? – e0k

+1

使用'stat'的速度會慢一點或更低,因爲這樣的代碼的運行時間大致與系統調用的數量成正比,'stat'是一個相當重的系統調用。這是在你承擔IO負擔之前:通過使用'stat',你可以在每個dir條目的inode上執行I​​O(重度隨機訪問),而不僅僅是讀取目錄表(緊湊線性讀取)。如果'_DIRENT_HAVE_D_TYPE'沒有被定義,你應該提供一個可移植的回退到'stat',否則**肯定使用'd_type' **如果你有它。 –