Why PathFileExists() not working?
I believe the problem is that you need to convert a char
string to a TSTR
and you aren't doing that.
You are using a type cast to coerce a pointer from type char *
to type LPCTSTR
but I think that doesn't actually work. As I understand it, a TCHAR
is either the same thing as char
or else it is a "wide char". I think you must have TCHAR
set to wide char or else you wouldn't have a problem.
I found a StackOverflow answer that includes information that may help you:
What is the simplest way to convert char[] to/from tchar[] in C/C++(ms)?
You might try calling MultiByteToWideChar()
and see if that fixes the problem.
Allan Ruin
Updated on June 04, 2022Comments
-
Allan Ruin about 2 years
I want to validate the existence of a file and after some search I think PathFileExists() may fit the job. However, the following code always show the file doesn't exist. To ensure the file really exist, I choose full path of cmd.exe as the test file path. I'm using windows 7 (x64)
#include "stdafx.h" #include <stdio.h> #include <windows.h> #include <shlwapi.h> #include <WinDef.h> #pragma comment( lib, "shlwapi.lib") int _tmain(int argc, _TCHAR* argv[]) { char path[] = "c:\\Windows\\System32\\cmd.exe"; LPCTSTR szPath = (LPCTSTR)path; if(!PathFileExists(szPath)) { printf("not exist\n"); }else{ printf("exists!\n"); } return 0; }
Can you explain about the problem?
UPDATE
Spend almost whole afternoon and figure out the problem. The PathFileExists() function expect second parameter of type
LPCTSTR
.However, the compiler can not correctly convertchar *
toLPCTSTR
then I includetchar.h
and using theTEXT
macro to initialize the pointer. Done. LPCTSTR lpPath = TEXT("c:\Windows\System32\cmd.exe"); The MSDN reference example code for PathFileExists() is kind of outdated. The reference example usedchar *
directly for PathFileExists() and can not pass compile in visual studio 2011 beta. And also , example code missed theusing namespace std;
Among all, I think @steveha 's answer is closest to the true problem. Thank you all guys.the final working code look like this:
#include "stdafx.h" #include <stdio.h> #include <windows.h> #include <shlwapi.h> #include <WinDef.h> #include <tchar.h> #pragma comment( lib, "shlwapi.lib") int _tmain(int argc, _TCHAR* argv[]) { LPCTSTR lpPath = TEXT("c:\\Windows\\System32\\cmd.exe"); if( PathFileExists(lpPath) == FALSE) { printf("not exist\n"); }else{ printf("exists!\n"); } return 0; }
Sorry foradding the solution here, but I really want to post some thought after a whole aternoon work and hope that helps other newbies.