2015-09-04 174 views
-2

我的目標是列出文本文件在特定的目錄中並讓用戶加載其中一個文件。FindFirstFile總是返回無效句柄

我使用Windows,在我的編譯器中預定義了Unicode。

問:FileHandle總是有INVALID_HANDLE_VALUE。這是什麼原因,我該如何糾正?

我最後的代碼如下所示:

ListAllTxtFiles(L"C:\\Users\\Tnc\Desktop\\Yazılım Çalışmaları\\Projects\\Oyun Projem\\data\\SaveFiles\\"); 

void ListAllTxtFiles(const wchar_t *Directory) 
{ 
    TCHAR Buffer[2048]; 
    wsprintf(Buffer, L"s%*.txt", Directory);//there are security considerations about this function 

    WIN32_FIND_DATAW FindData; 
    HANDLE FileHandle = FindFirstFileW(Buffer, &FindData); 

    if (FileHandle == INVALID_HANDLE_VALUE) 
    { 
     printf("Could not find any files..\n"); 
    } 
    else 
    { 
     do 
     { 
      printf("Found %s\\%s\n", Directory, FindData.cFileName); 

     } while (FindNextFile(FileHandle, &FindData)); 
     CloseHandle(FileHandle); 
    } 
} 
+0

您是否嘗試過從['GetLastError'](https://msdn.microsoft.com/en-us/library/windows/desktop/ms679360%28v=vs.85%29.aspx)打印結果? –

+0

'GetLastError'會爲你解答這個問題。最有可能的路徑是不正確的。 –

+0

約翰已經回答了你的問題。 'wsprintf()'中的格式字符串格式錯誤,導致'Buffer'接收錯誤的數據,所以'FindFirstFileW()'失敗。注意,你直接使用'FindFirstFileW()',因此'Buffer'應該被聲明爲'WCHAR'而不是'TCHAR','wsprintf()'應該是'wsprintfW()'。由於'cFileName'是'WIN32_FIND_DATAW'中的'WCHAR []',要將它打印爲Unicode字符串,則需要使用'wprintf()'而不是'printf()',或者至少使用'%ls在'printf()'中代替'%s'。 –

回答

1
wsprintf(Buffer, L"s%*.txt", Directory); 

應該

wsprintf(Buffer, L"%s*.txt", Directory); 

你剛收到你們的wsprintf格式字符串錯誤。

+0

如果你知道我花了多少小時來解決這個問題,你會因爲悲傷而哭泣。謝謝:D – bfkjohns

+0

但我只能得到文件的第一個字母。例如,我得到一個叫做「what」的字母w .txt文件。爲什麼會發生? – bfkjohns

+0

'因爲你可能應該使用'wprintf'打印或者其他的? –