如何检查目录是否存在?

发布于 2024-08-18 07:11:55 字数 180 浏览 4 评论 0原文

我将如何检查 FILE 是否是目录?我已经

if (file == NULL) {  
    fprintf(stderr, "%s: No such file\n", argv[1]);  
    return 1;  
} 

检查了节点是否存在,但我想知道它是目录还是文件。

How would I go about checking if a FILE is a directory? I have

if (file == NULL) {  
    fprintf(stderr, "%s: No such file\n", argv[1]);  
    return 1;  
} 

and that checks if the node exists at all, but I want to know if it's a dir or a file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

韵柒 2024-08-25 07:11:55

文件名本身不包含任何关于它们是否存在或它们是否是目录的信息 - 有人可以在您的下面更改它。您想要做的是运行一个库调用,即 stat(2),它会报告文件是否存在以及文件是什么。从手册页来看,

[ENOENT]           The named file does not exist.

有一个错误代码报告(在 errno 中)该文件不存在。如果它确实存在,您可能希望检查它是否实际上是一个目录而不是常规文件。您可以通过检查返回的结构中的 st_mode 来完成此操作:

The status information word st_mode has the following bits:
...
#define        S_IFDIR  0040000  /* directory */

检查联机帮助页以获取更多信息。

Filenames themselves don't carry any information about whether they exist or not or whether they are a directory with them - someone could change it out from under you. What you want to do is run a library call, namely stat(2), which reports back if the file exists or not and what it is. From the man page,

[ENOENT]           The named file does not exist.

So there's an error code which reports (in errno) that the file does not exist. If it does exist, you may wish to check that it is actually a directory and not a regular file. You do this by checking st_mode in the struct returned:

The status information word st_mode has the following bits:
...
#define        S_IFDIR  0040000  /* directory */

Check the manpage for further information.

时光礼记 2024-08-25 07:11:55
struct stat st;
if(stat("/directory",&st) == 0) 
        printf(" /directory is present\n");
struct stat st;
if(stat("/directory",&st) == 0) 
        printf(" /directory is present\n");
楠木可依 2024-08-25 07:11:55

使用 opendir 尝试将其作为目录打开。如果返回一个空指针,那么它显然不是一个目录:)

这是您的问题的片段:

  #include <stdio.h>
  #include <dirent.h>

   ...

  DIR  *dip;
  if ((dip = opendir(argv[1])) == NULL)
  {         
     printf("not a directory");
  }
  else closedir(dip);

use opendir to try and open it as a directory. If that returns a null pointer it's clearly not a directory :)

Here's a snippet for your question:

  #include <stdio.h>
  #include <dirent.h>

   ...

  DIR  *dip;
  if ((dip = opendir(argv[1])) == NULL)
  {         
     printf("not a directory");
  }
  else closedir(dip);
↙厌世 2024-08-25 07:11:55

如果您使用 *nix,请使用 stat()。

If you're using *nix, stat().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文