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

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

问题描述

我不能在线找到我的问题的解决方案。



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



有什么方便的方法吗?

解决方案

POSIX系统有两个相关功能: stat )和lstat()。这些用于查找路径名是指具有访问权限的实际对象,如果是,则返回的数据会告诉您是什么类型的对象。 stat() lstat()之间的区别是,如果您给的名称是一个符号链接, stat()遵循符号链接(或链接如果链接在一起),并在链接链结尾的对象上报告,而 lstat( )报告符号链接本身。

  #include< sys / stat.h> 

struct stat sb;

if(stat(pathname,& sb)== 0&&S_ISDIR(sb.st_mode))
{
...它是一个目录.. 。
}

如果函数表示成功,则使用S_ISDIR()宏来自 < sys / stat.h> 来确定文件是否实际上是一个目录。



您还可以使用其他 S_IS * 宏:




  • S_ISDIR —目录

  • S_ISREG —常规文件

  • S_ISCHR —字符设备

  • S_ISBLK —阻止设备

  • S_ISFIFO — FIFO

  • S_ISLNK —符号链接

  • S_ISSOCK —套接字



(某些系统也提供其他一些文件类型; S_ISDOOR 例如在Solaris上可用)。


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

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?

解决方案

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.

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

  • 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

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

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

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