目录存在时处理mkdir(C语言)

时间:2021-11-17 12:36:10

I'm trying to get a function made that will create a directory for use in a program, but will fail nicely when the directory already exists. Right now I'm doing

我正在尝试创建一个函数,它将创建一个在程序中使用的目录,但是当目录已经存在时会很好地失败。现在我正在做

if (mkdir(path, RW)<0)
{
error out and return
}

My problem is that mkdir returns -1 for what I think of as "real errors" (no access, no space, etc..) as well as for the directory already existing. I do want to error out in every error case aside from directory already exists. Any advice?

我的问题是mkdir返回-1,因为我认为是“真正的错误”(没有访问权限,没有空间等等)以及已经存在的目录。我确实希望在目录已存在的每个错误情况下都出错。任何建议?

Reference: http://linux.die.net/man/3/mkdir

参考:http://linux.die.net/man/3/mkdir

2 个解决方案

#1


1  

You should do the mkdir first, since doing a stat first will be more vulnerable to race conditions. On the line where you have

你应该先做mkdir,因为先做一个stat会更容易受到竞争条件的影响。在你的线上

error out and return

you should check first if errno is EEXIST (which would occur if there was already a file or directory), and in that special case, do a stat to determine if there was actually a directory (versus a file or special device, etc).

你应该先检查errno是否是EEXIST(如果已有文件或目录就会出现),在这种特殊情况下,做一个stat来确定是否确实存在一个目录(相对于文件或特殊设备等)。

A race-condition refers to scenarios where more than one process is creating, deleting and using the directories (or files). For example:

竞争条件是指多个进程正在创建,删除和使用目录(或文件)的情况。例如:

#2


1  

basically this is what I do:

基本上这就是我所做的:

errno = 0;
int dir_result = mkdir(dir_path, 0755);
if(dir_result != 0 && errno != EEXIST){
    //errors here   
}
else{
    //your code here
}

Regards.

问候。

#1


1  

You should do the mkdir first, since doing a stat first will be more vulnerable to race conditions. On the line where you have

你应该先做mkdir,因为先做一个stat会更容易受到竞争条件的影响。在你的线上

error out and return

you should check first if errno is EEXIST (which would occur if there was already a file or directory), and in that special case, do a stat to determine if there was actually a directory (versus a file or special device, etc).

你应该先检查errno是否是EEXIST(如果已有文件或目录就会出现),在这种特殊情况下,做一个stat来确定是否确实存在一个目录(相对于文件或特殊设备等)。

A race-condition refers to scenarios where more than one process is creating, deleting and using the directories (or files). For example:

竞争条件是指多个进程正在创建,删除和使用目录(或文件)的情况。例如:

#2


1  

basically this is what I do:

基本上这就是我所做的:

errno = 0;
int dir_result = mkdir(dir_path, 0755);
if(dir_result != 0 && errno != EEXIST){
    //errors here   
}
else{
    //your code here
}

Regards.

问候。