Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - fopen invalid file

Tags:

c

fopen

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.

Thanks

like image 686
Waypoint Avatar asked Apr 10 '11 14:04

Waypoint


2 Answers

in your param list:

FILE pFile ;

then:

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

if (pFile == NULL)
printf("No Such File !! ");
like image 56
Batman Avatar answered Sep 22 '22 12:09

Batman


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.

like image 29
Mat Avatar answered Sep 22 '22 12:09

Mat