Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   file - exceptions (http://www.go4expert.com/forums/file-exceptions-t23674/)

heidik 26Oct2010 17:29

file - exceptions
 
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 26Oct2010 17:29

Re: file - exceptions
 
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 1Nov2010 18:50

Re: file - exceptions
 
- 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


All times are GMT +5.5. The time now is 11:29.