C 检查目录是否存在的更快方法

发布于 2025-01-06 02:00:21 字数 126 浏览 2 评论 0原文

我正在使用 opendir 函数来检查目录是否存在。问题是我在一个巨大的循环中使用它,并且它正在给我的应用程序使用的内存充气。

检查 C 中目录是否存在的最佳(最快)方法是什么?如果不存在,创建它的最佳(最快)方法是什么?

I'm using opendir function to check if a directory exists. The problem is that I'm using it on a massive loop and it's inflating the ram used by my app.

What is the best (fastest) way to check if a directory exists in C? What is the best (fastest) way to create it if doesn't exists?

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

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

发布评论

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

评论(5

暮倦 2025-01-13 02:00:21

考虑使用statS_ISDIR(s.st_mode) 会告诉您它是否是一个目录。

样本:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

...
struct stat s;
int err = stat("/path/to/possible_dir", &s);
if(-1 == err) {
    if(ENOENT == errno) {
        /* does not exist */
    } else {
        perror("stat");
        exit(1);
    }
} else {
    if(S_ISDIR(s.st_mode)) {
        /* it's a dir */
    } else {
        /* exists but is no dir */
    }
}
...

Consider using stat. S_ISDIR(s.st_mode) will tell you if it's a directory.

Sample:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

...
struct stat s;
int err = stat("/path/to/possible_dir", &s);
if(-1 == err) {
    if(ENOENT == errno) {
        /* does not exist */
    } else {
        perror("stat");
        exit(1);
    }
} else {
    if(S_ISDIR(s.st_mode)) {
        /* it's a dir */
    } else {
        /* exists but is no dir */
    }
}
...
墨洒年华 2025-01-13 02:00:21

您可以调用mkdir()。如果该目录不存在,则将创建该目录并返回0。如果目录存在,则将返回 -1,并将 errno 设置为 EEXIST

You could call mkdir(). If the directory does not exist then it will be created and 0 will be returned. If the directory exists then -1 will be returned and errno will be set to EEXIST.

乜一 2025-01-13 02:00:21

我更喜欢使用 access()

if (0 != access("/path/to/possible_dir/", F_OK)) {
  if (ENOENT == errno) {
     // does not exist
  }
  if (ENOTDIR == errno) {
     // not a directory
  }
}

如果你确保尾随 / 在目录名称中,这非常有效。

I prefer using access()

if (0 != access("/path/to/possible_dir/", F_OK)) {
  if (ENOENT == errno) {
     // does not exist
  }
  if (ENOTDIR == errno) {
     // not a directory
  }
}

If you ensure a trailing / in the directory name, this works perfectly.

破晓 2025-01-13 02:00:21

如果可用的话,我会使用 stat() 。

I would use stat(), if available.

疑心病 2025-01-13 02:00:21

听起来你有内存泄漏。只要您记得在成功打开目录后始终调用 closedir,调用 opendir 就不应该增加应用程序的 RAM。另外,请确保释放分配用于计算目录名称的所有缓冲区。

It sounds like you have a memory leak. Calling opendir should not inflate the RAM of your app as long as you remember to always call closedir after successfully opening a directory. Also, make sure you are freeing any buffers you allocated to compute the directory name.

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