微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

unix – 跨平台的方式来测试一个文件是否是一个目录

目前我有一些代码(精简和删除一堆错误检查):
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头是crossplatform(对于POSIX机器).有什么建议么.

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

The struct dirent deFinition in solaris does not contain the d_type field. You would need to make the changes as follows

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

changes to

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)遵循标准.

原文地址:https://www.jb51.cc/bash/386276.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐