which os does your program run on? which specific programming language do you use? and what is file.fail()?

trying to answer your question:
1. search for "stat()"
2. you could check if your programming language has a function called "int file_exists(char *filename)" or similar.
3. you could read the permissions and ownership first from the file and then check the current uid/gid against that. err. the first would fail already for "file not found"... ;)
4. afaik there should be a function getLastError() or similar where you can read the last error-code. and another function that outputs the osīs default error string for this error.