2012-06-11 267 views
2

我想驗證一個文件的存在和一些搜索後,我認爲PathFileExists()可能適合這項工作。但是,以下代碼始終顯示該文件不存在。爲確保文件真的存在,我選擇完整路徑cmd.exe作爲測試文件路徑。我正在使用Windows 7(x64)爲什麼PathFileExists()不工作?

#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; 
} 

你能解釋一下這個問題嗎?

UPDATE

花幾乎整個下午,並找出問題。 PathFileExists()函數需要LPCTSTR類型的第二個參數。但是,編譯器無法正確地將char *轉換爲LPCTSTR,然後我包含tchar.h並使用TEXT宏來初始化指針。完成。 LPCTSTR lpPath = TEXT(「c:\ Windows \ System32 \ cmd.exe」); The MSDN reference example code for PathFileExists()是一種過時。該參考示例直接使用char *用於PathFileExists(),並且無法在Visual Studio 2011測試版中傳遞編譯。還有,示例代碼錯過了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; 
} 

對不起這裏foradding的解決方案,但我真的想後整體aternoon工作,並希望幫助其他新手張貼一些思考。

+1

嘗試在失敗後調用[GetLastError](http://msdn.microsoft.com/en-us/library/windows/desktop/ms679360(v = vs.85).aspx),查看出了什麼問題。 – ugoren

+1

請不要道歉在這裏添加解決方案;太棒了*。現在你的問題對於在StackOverflow上找到它的其他人將會非常有幫助。我自己的回答給了你一個線索,但並不是一個完整的答案,你發佈了一個完整的答案真是太棒了。我已經給你+1了,但如果可以的話,我會再給+1。 – steveha

+0

該參考文獻並未過時;您可以指定應用程序在項目設置中是使用單字節還是單字節字符串(常規>字符集)。這會影響像LPCTSTR這樣的宏是否擴展爲'wchar_t const *'或'char const *',並且大多數API函數可以擴展爲'PathFileExistsW'或'PathFileExistsA'。 – riv

回答

1

我認爲問題在於您需要將char字符串轉換爲TSTR而您並未這​​麼做。

您正在使用類型轉換來強制char *類型的指針輸入LPCTSTR,但我認爲這實際上不起作用。據我瞭解,TCHAR要麼是char,要麼是「寬字符」。我認爲你必須有TCHAR設置爲寬字符,否則你不會有問題。

我發現一個StackOverflow的答案,其中包括信息,可以幫助你:

What is the simplest way to convert char[] to/from tchar[] in C/C++(ms)?

您可以嘗試打電話MultiByteToWideChar(),看看是否能解決問題。