检查是否在UNIX(系统调用)存在的目录 [英] Checking if a directory exists in Unix (system call)

查看:139
本文介绍了检查是否在UNIX(系统调用)存在的目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能够在网上找到一个解决我的问题。

I am not able to find a solution to my problem online.

我想调用一个函数在Unix中,传递一个目录的路径,并知道它的存在。 执行opendir()如果某个目录不存在返回一个错误,但我的目标不是实际打开,检查错误,如果没有错误关闭它,而只是检查一个文件是一个目录或没有。

I would like to call a function in Unix, pass in the path of a directory, and know if it exists. opendir() returns an error if a directory does not exist, but my goal is not to actually open, check the error, close it if no error, but rather just check if a file is a directory or not.

有任何方便的方式做到这一点吗?

Is there any convenient way to do that please?

推荐答案

有关于POSIX系统是两个相关的功能:的 STAT()和LSTAT()。这些都是用来找出路径是否指的是您有权访问一个实际的对象,如果是这样,返回的数据告诉你它是什么类型的对象。 之间)LSTAT的不同状态(()是,如果你给的名字是一个符号链接, STAT()遵循符号链接(或者如果它们链接在一起的链接)的链接链末端的对象,而 LSTAT上报告( )符号链接本身的报告。

There are two relevant functions on POSIX systems: stat() and lstat(). These are used to find out whether a pathname refers to an actual object that you have permission to access, and if so, the data returned tells you what type of object it is. The difference between stat() and lstat() is that if the name you give is a symbolic link, stat() follows the symbolic link (or links if they are chained together) and reports on the object at the end of the chain of links, whereas lstat() reports on the symbolic link itself.

#include <sys/stat.h>

struct stat sb;

if (stat(pathname, &sb) == 0 && S_ISDIR(sb.st_mode))
{
    ...it is a directory...
}

如果该功能表明它是成功的,您使用S_ISDIR()宏从<一个href=\"http://www.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html\"><$c$c><sys/stat.h>以确定该文件是否实际上是一个目录

If the function indicates it was successful, you use the S_ISDIR() macro from <sys/stat.h> to determine whether the file is actually a directory.

您还可以检查使用其他 S_IS * 宏的其他文件类型:

You can also check for other file types using other S_IS* macros:


  • S_ISDIR &MDASH;目录

  • S_ISREG &MDASH;常规文件

  • S_ISCHR &MDASH;字符设备

  • S_ISBLK &MDASH;块设备

  • S_ISFIFO &MDASH; FIFO

  • S_ISLNK &MDASH;符号链接

  • S_ISSOCK &MDASH;插座

  • S_ISDIR — directory
  • S_ISREG — regular file
  • S_ISCHR — character device
  • S_ISBLK — block device
  • S_ISFIFO — FIFO
  • S_ISLNK — symbolic link
  • S_ISSOCK — socket

(有些系统提供一些其他类型的文件太多; S_ISDOOR 可在Solaris上,例如。)

(Some systems provide a few other file types too; S_ISDOOR is available on Solaris, for example.)

这篇关于检查是否在UNIX(系统调用)存在的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆