Skip to main content
Logo image

Section 15.5 Check Whether a File Exists

How do we know whether our file is actually open? What if we misspelled the filename for example? Or what if something went wrong during opening of the file? Or what if the file doesn’t even exist (but we thought it did)?
We use the fact that fopen() returns a special value if it is not able to open the file for some reason. That special value is a NULL pointer.

Investigate 15.6.

In Section 9.3, we learned that C interprets variables with the value of zero as false. Do you think that a null pointer will be interpreted as true or false?

admin.....open in new window

Note that in the case where the file isn’t actually open (indicated by fopen() returning a value of NULL) there is no need to close the file. In fact, even attempting to close the file in this case would lead to a runtime error: feel free to try it out!