c - struct dirent 在头文件中没有 de_type

标签 c libraries gnu dirent.h

<分区>

所以我有一个项目,我需要构建一个小型的简单文本 shell,它可以运行、编辑和读取目录中的文件。我有一个应该可以工作的小原型(prototype),除了当我编译时,我收到关于 d_type not found within the struct dirent used in dirent.h header file 的错误。

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

变量“de”的类型为 struct dirent*,正在检查它的类型,我收到错误:“struct 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 文件的引用不是因为其中一个在不同的库中,如果是这种情况,我该如何加载该库以便编译代码?

很抱歉发了这么长的帖子,非常感谢所有回答的人!

最佳答案

来自 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() 不遵循符号链接(symbolic link)。)struct stat 包含字段 st_mode,可以使用 POSIX 宏 S_ISDIR(m) 进行检查> 测试它是否是一个目录。


附录:请参阅下面@R.. 的评论和 this answer .总结:

  1. 使用正确的东西。将 -D_FILE_OFFSET_BITS=64 添加到您的编译器标志并使用 64 位文件偏移量构建。
  2. 使用预处理器宏 _DIRENT_HAVE_D_TYPE 检查您是否有 d_type。如果是这样,请使用 d_type。从目录表(如果可用)中获取所需信息比查找和读取文件的所有 inode 更有效。
  3. 作为后备措施,(按上述操作)使用 stat 读取 inode 并使用 S_ISDIR() 检查 st_mode宏(或类似检查)。

关于c - struct dirent 在头文件中没有 de_type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35215109/

相关文章:

python - python 是否导入所有列出的库?

mysql - 在 Glibc 2.11 上将 MySQL 5.1 更新到 5.6

c# - 用于 C# 的 minpack fortran .dll

Octave GNU : Undefined variable 'x' , 即使它被定义为函数输入

c - linux内核qemu执行make命令报错 "undefined reference to ` cprintf ''"

mobile - 如何读取.Contact文件?

c - 你能多快进行线性搜索?

c++ - 在 C++ 中合并两个库

c - 如何将 sscanf 与 argv 一起使用

c - 这个错误描述在 fread() 中意味着什么