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.)