为什么PathFileExists()不起作用?

我想validation文件的存在,经过一些搜索,我认为PathFileExists()可能适合这项工作。 但是,以下代码始终显示该文件不存在。 为确保文件确实存在,我选择cmd.exe的完整路径作为测试文件路径。 我正在使用Windows 7(x64)

#include "stdafx.h" #include  #include  #include  #include  #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; } 

你能解释一下这个问题吗?

UPDATE

花几乎整个下午来解决问题。 PathFileExists()函数需要LPCTSTR类型的第二个参数。但是,编译器无法正确地将char *转换为LPCTSTR然后我包含tchar.h并使用TEXT宏来初始化指针。 完成。 LPCTSTR lpPath = TEXT(“c:\ Windows \ System32 \ cmd.exe”); PathFileExists()的MSDN参考示例代码有点过时。 参考示例使用char *直接用于PathFileExists(),并且无法在Visual Studio 2011 beta中传递编译。 而且,示例代码错过了using namespace std; 其中,我认为@steveha的回答最接近真正的问题。 谢谢大家。

最终的工作代码如下所示:

 #include "stdafx.h" #include  #include  #include  #include  #include  #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; } 

对不起在这里找到解决方案,但我真的想在整个下午的工作后发表一些想法,希望能帮助其他新手。

我认为问题是你需要将一个char字符串转换为TSTR而你不是这样做的。

您正在使用类型转换来强制从类型char *到类型LPCTSTR的指针,但我认为这实际上不起作用。 据我了解, TCHARchar相同或者是“广泛的char”。 我认为你必须将TCHAR设置为宽字符,否则你就不会有问题。

我找到了一个StackOverflow答案,其中包含可能对您有所帮助的信息:

在C / C ++(ms)中将char []转换为/从tchar []的最简单方法是什么?

您可以尝试调用MultiByteToWideChar()并查看是否可以解决问题。