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

查看:28
本文介绍了检查 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().这些用于确定路径名是否引用了您有权访问的实际对象,如果是,则返回的数据会告诉您它是什么类型的对象.stat()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...
}

如果函数表明它成功了,您可以使用 判断文件是否真的是目录.

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 —目录
  • S_ISREG —常规文件
  • S_ISCHR —字符设备
  • S_ISBLK —块设备
  • S_ISFIFO —先进先出
  • S_ISLNK —符号链接
  • S_ISSOCK —插座
  • 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天全站免登陆