2014-10-20 40 views
1

我用下面的超超超級簡單的代碼來列出一個豬病的所有文件(Windows 8.1,Visual Studio速成2013,C++)的一個簡單的例子問題:C++ - 經與用FindFirstFile

#include <stdlib.h> 
#include <stdio.h> 
#include <sys/stat.h> 

#include <limits> 
#include <cstdio> 
#include <iostream> 
#include <fstream> 
#include <bitset> 

#include <windows.h> 
#include <tchar.h> 
#include <stdio.h> 


using namespace std; 


void get_file_list(string DATA_DIR) 
{ 
    HANDLE hFind; 
    WIN32_FIND_DATA data; 

    hFind = FindFirstFile(LPCWSTR(DATA_DIR.c_str()), &data); 

    if (hFind != INVALID_HANDLE_VALUE) { 
     do { 
      printf("%s\n", data.cFileName); 
     } while (FindNextFile(hFind, &data)); 
     FindClose(hFind); 
    } 
} 

int main(int argc, char** argv) 
{ 

    string DATA_DIR = "D:\\drobpox\\Dropbox\\BinaryDescriptors\\LFW\\DATA\\*.*"; 
    //string DATA_DIR = "c:\\Users\\GilLevi\\Downloads\\GraphsSURF\\GraphsSURF\\bark\\*.jpg"; 
    string OUT_DIR = "D:\\drobpox\\Dropbox\\BinaryDescriptors\\LFW\\LATCH_TXT_FILES\\LATCH8"; 


    get_file_list(DATA_DIR); 

} 

但是,我「hFind」總是等於「INVALID_HANDLE_VALUE」。我仔細檢查了路徑並嘗試了各種不同的路徑。

可能的原因是我正在運行64位應用程序並使用WIN32_FIND_DATA?

由於提前, 吉爾

+0

那麼當FindFirstFile失敗時,GetLastError會返回什麼? http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx – PaulMcKenzie 2014-10-20 21:56:14

+5

你不能簡化類型轉換爲LPCWSTR的字符串 – wimh 2014-10-20 21:56:52

回答

2

字符串轉換爲WideString的需要你分配內存和使用字符串轉換函數。 如果您不想更改該功能,最簡單的解決方案可能是使用非Unicode版本的FindFirstFile,通過將A添加到函數名和結構中;

WIN32_FIND_DATAA data; 

hFind = FindFirstFileA(DATA_DIR.c_str(), &data); 
+1

感謝您的幫助! – GilLevi 2014-10-25 16:04:49

3

由於您使用LPCWSTR,你應該使用std::wstring,在你的程序不std::string

另外,當投射到LPCWSTR時,沒有轉換魔法。這只是一個愚蠢的「C」劇組,除了關閉編譯器之外基本上什麼也不做。

+0

感謝您的幫助! – GilLevi 2014-10-25 16:04:29