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 convert char *
to LPCTSTR
then I include tchar.h
and using the TEXT
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 used char *
directly for PathFileExists() and can not pass compile in visual studio 2011 beta. And also , example code missed the using 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.