我想验证文件是否存在,经过一些搜索后我认为 PathFileExists() 可能适合这项工作。但是,下面的代码总是显示文件不存在。为确保文件真实存在,我选择cmd.exe的全路径作为测试文件路径。我正在使用 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;
}
你能解释一下这个问题吗?
更新
几乎花了整个下午的时间来找出问题所在。
PathFileExists() 函数需要 LPCTSTR
类型的第二个参数。但是,编译器无法将 char *
正确转换为 LPCTSTR
然后我包含 tchar.h
并使用 TEXT
宏来初始化指针。完毕。
LPCTSTR lpPath = TEXT("c:\Windows\System32\cmd.exe"); The MSDN reference example code for PathFileExists()有点过时了。引用示例直接为PathFileExists() 使用了char *
,在visual studio 2011 beta 中无法通过编译。而且,示例代码遗漏了 using namespace std;
其中,我认为@steveha 的回答最接近真正的问题。谢谢大家。
最终的工作代码如下所示:
#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;
}
很抱歉在这里添加解决方案,但我真的很想在整个下午的工作后发表一些想法,希望对其他新手有所帮助。
最佳答案
我认为问题在于您需要将 char
字符串转换为 TSTR
而您没有这样做。
您正在使用类型转换将指针从类型 char *
强制转换为类型 LPCTSTR
但我认为这实际上不起作用。据我了解,TCHAR
要么与 char
相同,要么就是“宽字符”。我认为您必须将 TCHAR
设置为宽字符,否则就不会有问题。
我找到了一个 StackOverflow 答案,其中包含可能对您有帮助的信息:
What is the simplest way to convert char[] to/from tchar[] in C/C++(ms)?
您可以尝试调用 MultiByteToWideChar()
并查看是否能解决问题。
关于c - 为什么 PathFileExists() 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10976071/