Home > OS >  check if file exists, case sensitive in C
check if file exists, case sensitive in C

Time:10-16

What is a good way to check that a file exists with case sensitivity in C on Windows?

I have got this to work by comparing the filename with the all the file entries in the directory of the filename. Is there a more efficient method in C?

CodePudding user response:

Use this:

WIN32_FIND_DATAA FindFileData;
HANDLE h = FindFirstFile(filenametocheck, &FindFileData);

now FindFileData.cFileName contains the filename as it is stored in NTFS.

All you need to do is compare filenametocheck with FindFileData.cFileName.

Don't forget to close the h handle with FindClose(h) and do error checking.

This works only for checking in the current directory, if filenametocheck contains a path (e.g ..\somefile.txt, or C:\\Somedir\Somefile.txt) you need to do some more work.

For further details read the documentation of FindFirstFile and possibly look into this sample.

Be aware that depending on what exactly you're trying to achieve, this may cause a TOCTOU bug as mentioned in a comment.

  • Related