stat vs mkdir与EEXIST [英] stat vs mkdir with EEXIST

查看:204
本文介绍了stat vs mkdir与EEXIST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果文件夹不存在,我需要创建它,所以我使用:

I need to create folder if it does not exists, so I use:

bool mkdir_if_not_exist(const char *dir)
{
  bool ret = false;
  if (dir) {
     // first check if folder exists
     struct stat folder_info;
     if (stat(dir, &folder_info) != 0) {
    if (errno == ENOENT) { // create folder
        if (mkdir(dir, S_IRWXU | S_IXGRP | S_IRGRP | S_IROTH | S_IXOTH) ?!= 0) // 755
        perror("mkdir");
        else
        ret = true;
    } else
         perror("stat");
    } else
         ret = true; ?// dir exists
     }
     return ret;
 }

仅在程序第一次运行时创建文件夹-之后仅是检查. 建议跳过stat调用,然后调用mkdir并针对EEXIST检查errno. 它会带来真正的好处吗?

The folder is created only during first run of program - after that it is just a check. There is a suggestion to skipping the stat call and call mkdir and check errno against EEXIST. Does it give real benefits?

推荐答案

有一点好处.查找"LBYL与EAFP" 或先了解一下"与更容易要求宽恕而不是允许".

There's a slight benefit. Look up 'LBYL vs EAFP' or 'Look Before You Leap' vs 'Easier to Ask Forgiveness than Permission'.

轻微的好处是stat()系统调用必须解析目录名称并到达inode-在这种情况下为丢失的inode-然后mkdir()必须执行相同的操作.当然,mkdir()所需的数据已经在内核缓冲池中,但是它仍然涉及两次遍历指定的路径,而不是一次遍历.因此,在这种情况下,使用EAFP的效率要比使用LBYL的效率高.

The slight benefit is that the stat() system call has to parse the directory name and get to the inode - or the missing inode in this case - and then mkdir() has to do the same. Granted, the data needed by mkdir() is already in the kernel buffer pool, but it still involves two traversals of the path specified instead of one. So, in this case, it is slightly more efficient to use EAFP than to use LBYL as you do.

但是,在普通程序中这是否真的可以衡量是值得商highly的.如果您无所事事,而是在各处创建目录,那么您可能会发现一种好处.但是,如果在程序开始时创建单个目录,那肯定是很小的效果,基本上是无法衡量的.

However, whether that is really a measurable effect in the average program is highly debatable. If you are doing nothing but create directories all over the place, then you might detect a benefit. But it is definitely a small effect, essentially unmeasurable, if you create a single directory at the start of a program.

您可能需要处理strcmp(dir, "/some/where/or/another") == 0的情况,但是尽管"/some/where"存在,但"/some/where/or"也不(必需)"/some/where/or/another"不存在.您当前的代码无法处理路径中间缺少的目录.它仅报告mkdir()将报告的ENOENT.您看起来的代码也不会检查dir实际上是否是目录-它只是假设如果存在,则它是目录.正确处理这些变化会比较棘手.

You might need to deal with the case where strcmp(dir, "/some/where/or/another") == 0 but although "/some/where" exists, neither "/some/where/or" nor (of necessity) "/some/where/or/another" exist. Your current code does not handle missing directories in the middle of the path. It just reports the ENOENT that mkdir() would report. Your code that looks does not check that dir actually is a directory, either - it just assumes that if it exists, it is a directory. Handling these variations properly is trickier.

这篇关于stat vs mkdir与EEXIST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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