how to check if a file is empty or does not exist

May 16, 2010 at 1:14pm
im trying to create a program the asks the user for a file name and then opens it and if he enters the wrong name it asks again! but when i purposely enter the wrong file name the first time and then i put in the right file name the second time it still says wrong name!!!
Le CodE:
do{
cout<<"Enter File Name : ";
cin>>nam;
cin.ignore();

filename.open(nam);
if (!filename)
{
cout << "wrong file name";
continue;

}

}while(!filename);


i have the whole program created and this is the only error!!!
please help asap!! i've got to submit my project and if i dont all my hard work will go to waste!
May 16, 2010 at 1:39pm
Assuming you're using ifstream filename and char * nam...

Look up open().
http://cplusplus.com/reference/iostream/ifstream/open/

If nam is a string... Use c_str().
http://cplusplus.com/reference/string/string/c_str/

-Albatross
Last edited on May 16, 2010 at 2:06pm
May 16, 2010 at 2:06pm
I don't think it is possible to tell if the file name was wrong. I think the best you can do is know that the open() command failed like this:

1
2
3
4
5
6
7
8
9

std::ifstream ifs;

ifs.open("my_text_file.txt");

if(!ifs.is_open())
{
    std::cout << "Could not open file." << std::endl;
}

May 17, 2010 at 1:04am
Yes, you are mixing two variables. A more correct way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
ifstream f;
string filename;

// Open the file
cout << "Enter file name> ";
while (true)
  {
  getline( cin, filename );
  f.open( filename.c_str() );
  if (f) break;

  cout << "I could not open that file.\n"
          "Please enter a valid file name> ";
  }

// Use the file f here.
...

// All done. Close the file.
f.close();

Notice that there is no way to escape until you type a valid file name. You might want to add a way out:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
ifstream f;
string filename;
cout << "Enter file name, or nothing to quit> ";
while (true)
  {
  getline( cin, filename );
  if (filename.empty())
    {
    cout << "OK, you want to quit.\n";
    return 1;
    }

  f.open( filename.c_str() );
  if (f) break;

  cout << "I could not open that file.\n"
          "Please enter a valid file name, or nothing to quit> ";
  }

...

Hope this helps.
Topic archived. No new replies allowed.