Unix 跨平台测试文件是否为目录的方法

Unix 跨平台测试文件是否为目录的方法,unix,posix,system-calls,dirent.h,Unix,Posix,System Calls,Dirent.h,目前我有一些代码,如(压缩并删除了一系列错误检查): 这在我的Linux机器上运行得很顺利。但是在另一台机器上(看起来像SunOS、sparc): 我在编译时遇到以下错误: error: structure has no member named `d_type' error: `DT_DIR' undeclared (first use in this function) 我认为dirent.h头是跨平台的(对于POSIX机器)。任何建议。参考: solaris中的struct dirent

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

这在我的Linux机器上运行得很顺利。但是在另一台机器上(看起来像SunOS、sparc):

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

error: structure has no member named `d_type'
error: `DT_DIR' undeclared (first use in this function)
我认为
dirent.h
头是跨平台的(对于POSIX机器)。任何建议。

参考:

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

更改为


由于
stat
也是POSIX标准,因此它应该更加跨平台。但是您可能希望使用
if((s.st_mode&s_IFMT)=s_IFDIR)
来遵循标准。

当我看到跨平台时,我倾向于假设您指的是Windows,可能还有OS/2.:-)仅针对Posix的答案很简单,而且已经有人给出了答案。实际上Posix为此定义了一个宏:
if(S_ISDIR(S.st_模式))
。当然,您还应该首先检查
stat()
是否成功。请注意,fstatat(2)可能比stat(2)更可取,因为
de->d_name
是相对于打开的目录的。我研究了如何使用fstatat(),它需要读取目录的文件描述符。这似乎不是一个合理的解决方案。
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)
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;
}