跨平台测试文件是否是目录的方式

时间:2010-02-04 07:00:51

标签: unix posix system-calls dirent.h

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

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机器)。任何建议。

1 个答案:

答案 0 :(得分:18)

参考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)来遵循标准。