0

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;
}

Edited by Obsidian_496: n/a

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by hag++
0

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
0

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
}

Edited by hag++: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.