在使用 open 函数时,会有这样的需求,如果文件存在,那么就报错退出,如果文件不存在那么就创建该文件。当然我们在执行 open 函数之前可以判断一下文件是否存在,但是这样做不仅多了一步,而且比较麻烦,其实使用 open 中的 O_EXCL 参数就可以解决这种问题。

1
int nRet = open("/home/mycode/mycode.txt", O_WRONLY  O_CREAT  O_EXCL, 0644);

当以上代码执行时,如果 /home/mycode/mycode.txt 文件存在,那么 nRet 会返回-1,并且 errno == EEXIST,我们可以通过以下两种方法来判断:

1
2
3
4
5
6
int nRet = open("/home/mycode/mycode.txt", O_WRONLY  O_CREAT  O_EXCL, 0644);
if (nRet < 0)
{
perror("open file error");
exit(1);
}
1
2
3
4
5
6
int nRet = open("/home/mycode/mycode.txt", O_WRONLY  O_CREAT  O_EXCL, 0644);
if (errno == EEXIST)
{
perror("open file error");
exit(1);
}

通过上面的代码就可以根据文件是否存在而执行不同的工作了。