file - exceptions

heidik's Avatar, Join Date: Oct 2010
Contributor
Could somebody please tell me how do I write a file in "try catch" block for checking if the file exists, if it is opened, if it is not empty. This is the error message I get when the file not exist or it is empty.

Code:
terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::substr
heidik's Avatar, Join Date: Oct 2010
Contributor
Could somebody please tell me how do I write a file in "try catch" block for checking if the file exists, if it is opened, if it is not empty. This is the error message I get when the file not exist or it is empty.

Code:
terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::substr
shifoo's Avatar, Join Date: Nov 2010
Newbie Member
- Checking if file exists [You can use _access to check]

#include <io.h>

if(_access(“C:\\directory\\filename.txt”, 0) == -1)
{
//File does not exist
}

- Checking if file is opened

You can use the normal way to open files and check if you can access and write to it. There is no way to tell if other processes have opened the file unless you check them. I think in linux you can check if the file is locked at that time.

- Checking if file is empth [You can use peek() to check]

First you open the file, then you use peek() from iostream to check if it returns eof. If so then the file is empty

UAT Student