如何读取目录中包含的所有文件 (WINDOWS)

How to Read all files contained in a directory (WINDOWS)

本文关键字:文件 WINDOWS 包含 何读取 读取      更新时间:2023-10-16

我需要传输目录中包含的所有文件。

我应该如何继续读取特定目录中的所有文件,然后通过套接字传输?

编辑:我对转移没有问题,只是不知道我应该怎么做才能下载完整的目录。

这是一个简单的版本,可以帮助您入门,因为如果我理解正确,您唯一的麻烦是检索文件列表而不是传输它们。通过一些递归,您还可以下降到子目录并一次性获取完整的列表(修改此示例很容易)。

// Returns files in the specified directory path.
vector<wstring> list_files(wstring path)
{
    vector<wstring> subdirs, matches;
    WIN32_FIND_DATA ffd;
    HANDLE hFind = FindFirstFile((path + L"\*.*").c_str(), &ffd);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        do
        {
            wstring filename = ffd.cFileName;
            if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
                matches.push_back(path + L"\" + filename);
        } while (FindNextFile(hFind, &ffd) != 0);
    }
    FindClose(hFind);
    return matches;
}

例:

vector<wstring> files = list_files("C:\pr0n");
// 'files' now contains 1,000 file entries. 
// Directories are not included.
// Now send them over individually.

请注意,如果您有兴趣,还有更好的跨平台替代方案,例如 boost FS。

这是来自 MDSN 的示例代码,但我像您一样对其进行了一点修改只想从当前目录中获取所有文件。我假设您正在使用 MFC。 如果没有,请参阅此列表。

void Recurse(LPCTSTR pstr)
{
   CFileFind finder;
   // build a string with wildcards
   CString strWildcard(pstr);
   strWildcard += _T("\*.*");
   // start working for files
   BOOL bWorking = finder.FindFile(strWildcard);
   while (bWorking)
   {
      bWorking = finder.FindNextFile();
      // skip . and .. files; otherwise, we'd
      // recur infinitely!
      if (finder.IsDots())
         continue;
      if (!finder.IsDirectory())
      {         
          CString str = finder.GetFilePath();
          AfxMessageBox( str );
      }
   }
   finder.Close();
}

要使用它,请致电:

Recurse(_T("C:\intel"));