[英]List files in directory C++
我正在嘗試使用此示例創建一個程序,該程序將列出Windows::Forms::ListBox
目錄中的所有文件名。
由於用戶不會進行任何輸入,因此我不需要void DisplayErrorBox(LPTSTR lpszFunction)
函數以及其他錯誤檢查功能。
當我單擊觸發事件的按鈕時,這就是列表框中顯示的內容。
o //&#o/
/ //
/ //
/ //
/ //
/ //
/ //
/ //
另外,每次我單擊按鈕時,只會出現一行。 應該在目錄中查找所有文件並列出它們,而不是每次單擊按鈕時都查找下一個文件。
我還想使用相對的strPath,而不是絕對的...到目前為止,這是我對代碼所做的事情:
private:
void List_Files()
{
std::string strPath = "C:\\Users\\Andre\\Dropbox\\Programmering privat\\Diablo III DPS Calculator\\Debug\\SavedProfiles";
TCHAR* Path = (TCHAR*)strPath.c_str();
WIN32_FIND_DATA ffd;
LARGE_INTEGER filesize;
TCHAR szDir[MAX_PATH];
size_t length_of_arg;
HANDLE hFind = INVALID_HANDLE_VALUE;
// Prepare string for use with FindFile functions. First, copy the
// string to a buffer, then append '\*' to the directory name.
StringCchCopy(szDir, MAX_PATH, Path);
StringCchCat(szDir, MAX_PATH, TEXT("\\*"));
// List all the files in the directory with some info about them.
do
{
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
//If it's a directory nothing should happen. Just continue with the next file.
}
else
{
//convert from wide char to narrow char array
char ch[260];
char DefChar = ' ';
WideCharToMultiByte(CP_ACP,0,(ffd.cFileName),-1, ch,260,&DefChar, NULL);
//A std:string using the char* constructor.
std::string str(ch);
String ^ sysStr = gcnew String(str.c_str());
MessageBox::Show("File Found", "NOTE");
ListBoxSavedFiles->Items->Add (sysStr);
}
}
while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
}
永遠不會調用FindFirstFile()
,您需要在調用FindNextFile()
之前先調用它:
HANDLE hFind = FindFirstFile(TEXT("C:\\Users\\Andre\\Dropbox\\Programmering privat\\Diablo III DPS Calculator\\Debug\\SavedProfiles\\*"), &ffd);
if (INVALID_HANDLE_VALUE != hFind)
{
do
{
//...
} while(FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
}
else
{
// Report failure.
}
如果您不介意使用Boost ,則可以使用directory_iterator
:
using boost::filesystem;
path p("some_dir");
for (directory_iterator it(p); it != directory_iterator(); ++it) {
cout << it->path() << endl;
}
它也可以在Windows上運行,而且看起來絕對簡單得多。 當然,您需要對當前代碼進行一些調整,但是從長遠來看,這是值得的。
(TCHAR*)strPath.c_str();
是錯的。 從對WideCharToMultiByte
的使用中,我知道(TCHAR*)strPath.c_str();
正在將char const*
強制轉換為wchar_t*
。 這不僅會丟失const
,而且寬度也是錯誤的。
如果您使用的是Visual Studio,則將配置設置更改為“ Use Multibyte Character set
。 這將使您的TCHAR東西無需任何強制轉換即可編譯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.