简体   繁体   English

如何确保文件存在并已打开

[英]How to make sure file exists and it is opened

I am trying to make a program which checks if a file exists, otherwise it creates and opens it.我正在尝试制作一个程序来检查文件是否存在,否则它会创建并打开它。 This is what I tried doing:这是我尝试做的:

fstream file("data.txt");
if (!file.is_open())
{
    ofstream file("data.txt");
    file.close();
}
fstream file("data.txt");

The program tries to open the data.txt file and if it does not exist, it creates it, but then it is a local, so I have to close and open it in the main function.程序尝试打开 data.txt 文件,如果它不存在,它会创建它,但它是本地的,所以我必须在主函数中关闭并打开它。 If the file already exists the I get the multiple instances error.如果文件已经存在,我会收到多个实例错误。 I tried closing the file before opening it but it still gives me the same error.我在打开文件之前尝试关闭它,但它仍然给我同样的错误。 Code:代码:

fstream file("data.txt");
if (!file.is_open())
{
    ofstream file("data.txt");
    file.close();
}
file.close();
fstream file("data.txt");

Is there a better way to do it than that?还有比这更好的方法吗? Thx for your time =) (yes, I have searched for answers before asking.)谢谢你的时间=)(是的,我在提问之前已经搜索了答案。)

Simply create a file stream without specifying without telling which file to open.只需创建一个文件流,无需指定打开哪个文件。

fstream file;
file.open("data.txt");

Then use .fail() to check if it has FAILED in opening the file然后使用.fail()检查它是否在打开文件时失败

if (fileStream.fail()) 
{
    ofstream file("data.txt");
}
file.open("data.txt");

Then open it again.然后再打开。 fstream (Filestream) is just simply a child of iostream which does not required to be initialized and can be declared you can read more about it over here fstream (Filestream) 只是 iostream 的一个子节点,不需要初始化并且可以声明,您可以在此处阅读有关它的更多信息

Also this is c and POSIX - maybe it is of interest, cause it is a fast and handy check if file exists.这也是 c 和 POSIX - 也许它很有趣,因为它可以快速方便地检查文件是否存在。

#include <unistd.h>
if(access(filename, F_OK ) == 1) // file exists
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM