1

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 variable in the if statement, so I have to close and open it in the main function. If the file already exists then I get a 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.)

sJames
  • 54
  • 10
  • Search before asking: * https://stackoverflow.com/questions/15667530/fstream-wont-create-a-file * https://stackoverflow.com/questions/8835888/stdfstream-doesnt-create-file – Gang YIN Sep 25 '20 at 01:33
  • also the constructor isnt the only way to open a file with a stream, you can call open as well. – Borgleader Sep 25 '20 at 01:36
  • @GangYin I did not search fstream won't create a file. Obviously this wasn't my problem – sJames Sep 25 '20 at 02:02

2 Answers2

2

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

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

Chass Long
  • 539
  • 4
  • 16
-1

Also this is c and POSIX - maybe it is of interest, cause it is a fast and handy check if file exists.

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