My program has to open a text file. I want it to give an error message if the file does not exist (or has a diferent name, which is the same, really).

I'm using a pretty old Borland compiler, because home assingnments are checked with it.

Compiler shows me this error:
Info :Compiling L:\algorithms\test.cpp
Error: test.cpp(6,22):'is_open' is not a member of 'ifstream'

#include <iostream>
#include <fstream>

int main () {
  ifstream myfile ("data.txt");
  if (myfile.is_open())
  {
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}

Recommended Answers

All 2 Replies

My program has to open a text file. I want it to give an error message if the file does not exist (or has a diferent name, which is the same, really).

I'm using a pretty old Borland compiler, because home assingnments are checked with it.

Compiler shows me this error:
Info :Compiling L:\algorithms\test.cpp
Error: test.cpp(6,22):'is_open' is not a member of 'ifstream'

#include <iostream>
#include <fstream>

int main () {
  ifstream myfile ("data.txt");
  if (myfile.is_open())
  {
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}

I have always done something like this

if (!myfile)
{
  // error message
// exit (1)
}
// do file stuff here

I have always done something like this

if (!myfile)
{
  // error message
// exit (1)
}
// do file stuff here

I usually do this as well..... however you can use the fail method which is contained in the newer fstream lib

ifstream someFile("whatever.txt");

if (someFile.fail())
{
   // put error message here and exit program
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.