RA.
RA.

Reputation: 1029

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?

Upvotes: 1

Views: 1297

Answers (2)

RA.
RA.

Reputation: 1029

I found the answer. Turns out Windows is always redirecting system32 to syswow64 while trying to access in 64-bit Windows. I had to use SysNative directory, even though it doesnt exist - Windows redirects it to the proper system32 directory.

Since Visual Studio 2012, application projects default to “Any CPU 32-bit preferred”. If you run such an executable on a 64-bit Windows operating system, then it will start as a 32-bit process and be affected by WOW64 file system redirection.

When a 32-bit process on 64-bit Windows tries to access "C:\Windows\System32", WOW64 redirects it to "C:\Windows\SysWOW64". There are several ways to access the real "C:\Windows\System32" directory:

  • Use "C:\Windows\SysNative", which WOW64 redirects to "C:\Windows\System32" even though it does not appear in directory listings. This is an easy way and unlikely to cause problems.
  • Use Wow64DisableWow64FsRedirection and Wow64RevertWow64FsRedirection.
  • Use a 64-bit process.

Source: https://social.msdn.microsoft.com/Forums/en-US/c54f8368-035e-478e-b988-b180a3c7e3da/file-not-found-for-existing-file-in-system32-directory?forum=csharpgeneral

Upvotes: 1

SingerOfTheFall
SingerOfTheFall

Reputation: 29966

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"

Upvotes: 4

Related Questions