Donald Duck Donald Duck - 4 years ago 309
C++ Question

WINAPI: File exists check fail

I want to check if a certain file exists in the specified location. I have been trying multiple solutions for that but seem like none of them work properly, since all of them return false.

There is no doubt that the file exists in the specified location.

Executable is being run as administrator, so I'm having the appropriate permissions.

Code I used:

#include <io.h>
#include <string>
#include <Shlwapi.h>

std::string str = "C:\WINDOWS\System32\iluminated.dll";
unsigned long attrib = GetFileAttributes(str.c_str());

bool exists1 = (attrib != INVALID_FILE_ATTRIBUTES &&
!(attrib & FILE_ATTRIBUTE_DIRECTORY)) &&
GetLastError() != ERROR_FILE_NOT_FOUND; // false
bool exists2 = ( _access( str.c_str(), 0 ) != -1 ); // false
bool exists3 = PathFileExists(str.c_str()) != 0; // false


Is there anything I'm doing wrong?

Answer Source

You should use double back slashes for paths, since if you use single back slashes in a string they are interpreted as command symbols (line \n, for example):

"C:\\WINDOWS\\System32\\iluminated.dll"

Alternatively, you can use forward slashes, they work on most operating systems:

"C:/WINDOWS/System32/iluminated.dll"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download