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 betwe开发者_运维技巧en 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.
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
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.
精彩评论