I'm programming in C and trying to write portable code.
My question is, how can I tell if a file exists and is readable?
I am currently using the code:
f = fopen(filename, "r");
if (f) printf("File exists!");
In my program, filename is set by the user, and should be considered as untrusted input (e.g. filename could be maliciously crafted).
My issue is that the above code is not robust. For example, when used on windows with the filename "PRN" it will print "File exists!" even though no such file exists on the filesystem.
I know I could filter out the reserved filenames on Windows, as there is only about a dozen of them, but that feels like a hack. Also, I only know what I know. Maybe there are other "reserved" or "special" names that I don't know about.
Is there any simple and portable way to determine if a file exists in C?
Alternatively, if I have to use an OS API, which function should I use?