如何在创建新文件之前检查文件是否存在 [英] How to check if a file exists before creating a new file

查看:66
本文介绍了如何在创建新文件之前检查文件是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向文件中输入一些内容,但我想先检查一下我要创建的文件名是否存在。如果是这样,即使该文件为空,我也不想创建任何文件。

I want to input some contents to a file, but I'd like to check first if a file with the name I wish to create exists. If so, I don't want to create any file, even if the file is empty.

我的尝试

bool CreateFile(char name[], char content[]){
     std::ofstream file(name);
     if(file){
         std::cout << "This account already exists" << std::endl;
        return false;
     }
     file << content;
     file.close();
     return true;
}

有什么方法可以做我想要的吗?

推荐答案

假设操作不是原子的就可以了,您可以这样做:

Assuming it is OK that the operation is not atomic, you can do:

if (std::ifstream(name))
{
     std::cout << "File already exists" << std::endl;
     return false;
}
std::ofstream file(name);
if (!file)
{
     std::cout << "File could not be created" << std::endl;
     return false;
}
... 

请注意,如果您运行多个线程尝试创建同一文件,并且肯定不会阻止第二个进程干扰文件的创建,因为您拥有 TOCTUI 问题。 [我们首先检查文件是否存在,然后创建文件-但其他人可能在检查和创建之间创建了文件-如果这很关键,则您需要做其他不能移植的操作]。

Note that this doesn't work if you run multiple threads trying to create the same file, and certainly will not prevent a second process from "interfering" with the file creation because you have TOCTUI problems. [We first check if the file exists, and then create it - but someone else could have created it in between the check and the creation - if that's critical, you will need to do something else, which isn't portable].

另一个问题是,如果您具有诸如文件不可读(因此我们无法打开它进行读取)但可写的权限,它将覆盖文件。

A further problem is if you have permissions such as the file is not readable (so we can't open it for read) but is writeable, it will overwrite the file.

在大多数情况下,这两项都不重要,因为您所关心的就是告诉某人您已经有一个类似的文件(或类似的文件)一种尽力而为的方法。

In MOST cases, neither of these things matter, because all you care about is telling someone that "you already have a file like that" (or something like that) in a "best effort" approach.

这篇关于如何在创建新文件之前检查文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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