Take the 2-minute tour ×

I am wondering, how to check if I am opening file which exists with fopen? I want to diplay some message, when user selects file with bad name. Is must be some simple checking, but I am not able to solve it.


share|improve this question

5 Answers 5

up vote 0 down vote accepted

in your param list:

FILE pFile ;


  pFile = fopen ("myfile.txt","r");

if (pFile == NULL)
printf("No Such File !! ");
share|improve this answer
that's not a good error message at all. "no such file" is only one of the possible failures. –  Mat Apr 10 '11 at 14:09
This is the only possible option, because if file is corrupt he wont load as a program for example, but he will be able to read its characters char by char(or line or more). –  Batman Apr 11 '11 at 7:05
No it's not. It could be a permission problem on the file or the path. It could be a resource allocation error also (fopen can call malloc, which can fail). Saying "no such file" when the problem could be completely different is bad practice and will make debugging harder. –  Mat Apr 11 '11 at 7:16

To make it even clearer:

f = fopen("some-file-name.ext", "r"); if (f == NULL) reporterror();

But, probably you don't want to use fopen for checking existence and access right. You should look at stat and access. Both available in C libraries and using man

share|improve this answer
+1 for access/stat. –  Duck Apr 10 '11 at 14:35
Note that access and stat are not C (they are POSIX). –  Jens Apr 10 '11 at 16:56
@Jens - You're right. I remember access being on every platform I worked on but it apparently isn't standard. –  Duck Apr 15 '11 at 16:12

When fopen fails, it returns NULL and sets errno to indicate the type of error.

Check the return value, and if it's NULL check errno. You can use functions like perror or strerror to display simple messages about those errors.

share|improve this answer

It's simple: the returned FILE* pointer will be null if file doesn't exists.

Of course this assumes you are opening it in r, read mode.

share|improve this answer
Yes, but it will be as well NULL if he doesn't have appropriate permissions for example. –  Blagovest Buyukliev Apr 10 '11 at 14:06
Therefor you need to know what you want your code to do. –  Batman Apr 10 '11 at 14:14
What about the good old perror? –  Jack Apr 10 '11 at 14:23

See the possible errors for open: http://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html

However, I think you'll have a hard time finding a way to determine that a filename was invalid. On most systems (except Windows) any string that's not overly long is potentially valid (modulo / being interpreted as a path separator).

share|improve this answer

Your Answer


