Waypoint
Waypoint

Reputation: 17743

C - fopen invalid file

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

Upvotes: 6

Views: 18661

Answers (6)

Chiara Tumminelli
Chiara Tumminelli

Reputation: 362

fopen() function opens the file whose name is specified in the parameter filename and associates it with a stream that can be identified in future operations by the FILE pointer returned.

FILE *try_to_open = fopen("Document.txt", "r");    //READ ONLY

If the file is successfully opened, function returns a pointer to a FILE object that can be used to identify the stream on future operations; otherwise, a null pointer is returned. So, if you want to check that file has been opened correctly, just check that pointer is not null, in this way:

if (try_to_open == NULL){
    puts("Opening file failed.");
} else {
    puts("File opened successfully.");

Upvotes: 1

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

See the possible errors for open:

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).

Upvotes: 1

seth
seth

Reputation: 345

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

Upvotes: 1

Mat
Mat

Reputation: 206659

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.

Upvotes: 3

Batman
Batman

Reputation: 1324

in your param list:

FILE pFile ;

then:

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

if (pFile == NULL)
printf("No Such File !! ");

Upvotes: 3

Jack
Jack

Reputation: 133557

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.

Upvotes: 0

Related Questions