Antti Karanta
Antti Karanta

Reputation: 137

How to determine in Windows whether file exists, does not exist or this can't be known (using c)

I have to clean up from a list of files the ones that do not exist any more. The ones whose status is indeterminable should be given a warning about but left on the list. Sounds simple enough. However, the c functions I tried to solve this with don't seem to give a reliable answer between whether the file really does not exist or it e.g. resides on a network share that is at the moment inaccessible (e.g. due to network problems).

stat function sets errno to ENOENT if the file can't be reached, so that is indistinguishable from the file not actually existing.

FindFirstFile in some cases sets last error (obtainable with GetLastError()) to ERROR_PATH_NOT_FOUND when the network share can't be reached. Yes, I know FindFirstFile is for reading directories, but I thought I could deduce what I need to know by the error code it sets.

Also GetFileAttributes seems to in some cases set last error to ERROR_PATH_NOT_FOUND in case the network drive is unreachable.

Upvotes: 0

Views: 666

Answers (2)

rnd
rnd

Reputation: 11

if((f = fopen(file, "r")) == NULL){
    //File does not exist or can not be read
}else{
    //File exists
    fclose(f);
}

Drawbacks:

You don't know if a file is nonexistent or just can't be read (privileges etc),

On the other hand, it is 100% portable.

Upvotes: 1

imaximchuk
imaximchuk

Reputation: 748

CreateFile does set LastError to 0x35 (network path not found) if network share is not availiable and to 0x2 (system cannot find the path specified) if share is availiable, but file does not exist

Upvotes: 1

Related Questions