c++ - 列出目录 C++ 中的文件

标签 c++ winapi

我正在尝试使用 this example 创建一个程序,该程序将列出 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.
}

关于c++ - 列出目录 C++ 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11362771/

相关文章:

c++ - ItkVtkGlue 的问题

delphi - 如何判断Windows任务栏的 "autohide"是否启用?

c - 用于在 C 中重命名文件的 Win32 API

c++ - 具有 Windows 7 外观的消息框

c++ - 远程嵌入式设备上带有核心文件的 GDB - 如何获取有关回溯的更多信息?

java - 使用双数组的最佳实践

c++ - Visual Studio 2012 中的单元测试 C++ 控制台应用程序

c++ - 分配给临时(如 5 = 10 但对于用户定义的类型)

c - 使用缓冲区的 Windows AlphaBlend

sockets - IOCP 的 RIO 比事件有什么优势吗?