Checking to see if file opened (File I/O)

I can't believe I'm asking this because I've done this before, but for some reason it's not working. I'm asking the user to give me the name of a file. If the file doesn't exist or does not open, I want it to prompt them again until they give me a good file name. The code I'm using now is:

1
2
3
4
5
6
7
8
9
10
11
12
	do
	{
	cout << "\nPlease enter the file path: ";
	cin >> file;
	
	fileName.open(file.c_str( ));
	if (fileName.fail())
	{
	cout << "\Error!";
	fileName.clear( );
	}
	}while (fileName.fail());


Everything works great if they give me a good file name, but that's it... If they give me a bad file name, it doesn't work. Any suggestions?

S
You can use is_open() to check if the file was successfully opened. If file is ! open then cout the Error and force rentry via a loop.

example of use:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <fstream>
using namespace std;

int main () {

  fstream filestr;
  filestr.open ("test.txt");
  if (filestr.is_open())
  {
    filestr << "File successfully open";
    filestr.close();
  }
  else
  {
    cout << "Error opening file";
  }
  return 0;
}


Hope this helps.
I think that if fileName was for output only the file would be created, try enabling the ios::in flag: fileName.open(file.c_str(),ios::in|ios::out);
Thanks Return, works perfectly!
Two concerns you ought to have:

1. 'fileName' should be a string, and 'file' should be an [i]fstream

2. You should be using getline() to get the filename, as the >> operator breaks on spaces (even those the user explicitly quotes):
1
2
  cout << "\nPlease enter the file path: ";
  getline( cin, fileName );


Enjoy!
Topic archived. No new replies allowed.