0

I am a novice in c++ and I am a little confused/overwhelmed by all the different ways there are to check if a text file exists.

I have created a text file:

ofstream myfile;
myfile.open("actFile.txt");

Which I can see in the directory. But how would I use that to see if it already exists?

Would this work?

ofstream myfile;
if (myfile.good())
{
  // read, write
} else
{
  myfile.open("actFile.txt");
}
JHobern
  • 866
  • 1
  • 13
  • 20
trama
  • 1,271
  • 3
  • 14
  • 24

1 Answers1

1

Use the is_open() method:

std::string filename = "myfile";
std::ifstream ifile(filename.c_str());

if (!ifile.is_open()) {
    std::cerr << "There was a problem opening the input file" << std::endl;
}

REFERENCE: http://www.cplusplus.com/reference/fstream/fstream/is_open/

jrd1
  • 10,358
  • 4
  • 34
  • 51