【问题标题】:Cross platform way of testing whether a file is a directory跨平台测试文件是否为目录的方法
【发布时间】:2011-01-12 23:09:50
【问题描述】:

目前我有一些类似的代码(压缩并删除了一堆错误检查):

dp = readdir(dir);
if (dp->d_type == DT_DIR) {
}

这在我的 Linux 机器上运行良好。然而在另一台机器上(看起来像 SunOS,sparc):

SunOS HOST 5.10 Generic_127127-11 sun4u sparc SUNW,Ultra-5_10

我在编译时收到以下错误:

error: structure has no member named `d_type'
error: `DT_DIR' undeclared (first use in this function)

我认为 dirent.h 标头是跨平台的(用于 POSIX 机器)。任何建议。

【问题讨论】:

  • 当我看到跨平台时,我倾向于假设您的意思是 Windows,也可能是 OS/2。 :-) Posix 的答案很简单,而且有人已经给出了答案。

标签: unix posix system-calls dirent.h


【解决方案1】:

参考http://www.nexenta.org/os/Porting_Codefixes:

solaris 中的 struct dirent 定义不包含 d_type 字段。您需要进行如下更改

if (de->d_type == DT_DIR)
{
   return 0;
}

更改为

struct stat s; /*include sys/stat.h if necessary */
..
..
stat(de->d_name, &s);
if (s.st_mode & S_IFDIR)
{
  return 0;
}

由于stat 也是 POSIX 标准,它应该更加跨平台。但您可能想使用if ((s.st_mode & S_IFMT) == S_IFDIR) 来遵循标准。

【讨论】:

  • 实际上POSIX为此定义了一个宏:if (S_ISDIR(s.st_mode))。当然你也应该先检查stat()是否成功。
  • 请注意,fstatat (2) 可能比 stat (2) 更可取,因为de->d_name 与打开的目录相关。
  • 我研究过使用 fstatat() ,它需要一个文件描述符来读取正在读取的目录。这似乎不是一个合理的解决方案。
猜你喜欢
  • 2017-08-11
  • 1970-01-01
  • 1970-01-01
  • 2011-04-17
  • 1970-01-01
  • 2013-07-04
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多