【发布时间】:2020-08-06 02:39:14
【问题描述】:
我是 C++ 新手,我需要在驱动器中搜索特定文件并将其显示或在列表框中列出。
这是我到目前为止所拥有的。我在论坛中找到的一些点点滴滴和我添加的东西。
我的问题是如何将它们组合在一起。假设我正在搜索一个名为“test.txt”的文件
谢谢!
// search for drives
char* szSingleDrive;
DWORD dwSize = MAX_PATH;
char szLogicalDrives[MAX_PATH] = { 0 };
DWORD dwResult = GetLogicalDriveStrings(dwSize, szLogicalDrives);
UINT logicalDrive = GetDriveType(szLogicalDrives);
bool IsPhysicalDrive(string drives)
{
if (logicalDrive == 3)
{
return logicalDrive;
}
}
// function to look thru directories.
void FindFile(std::string directory)
{
std::string tmp = directory + "\\*";
WIN32_FIND_DATA file;
HANDLE search_handle = FindFirstFile(tmp.c_str(), &file);
if (search_handle != INVALID_HANDLE_VALUE)
{
std::vector<std::wstring> directories;
do
{
//std::wcout << file.cFileName << std::endl;
//::MessageBox(NULL, file.cFileName, "", MB_OK); // message box to verify that it's working
if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if ((!lstrcmp(file.cFileName, ".")) || (!lstrcmp(file.cFileName, "..")))
continue;
}
//std::wcout << file.cFileName << std::endl;
::MessageBox(NULL, file.cFileName, "", MB_OK);
directory += "\\" + std::string(file.cFileName);
FindFile(directory);
}
while (FindNextFile(search_handle, &file));
if (GetLastError() != 18) // Error code 18: No more files left
FindClose(search_handle);
//CloseHandle(search_handle);
}
}
FindFile("C:\\"); // <-- this should spin thru different drives (physical drives from the function)
【问题讨论】:
-
看来您使用的是 Windows。如果您使用的是较新版本的 Visual Studio,那么我们可以使用
std::filesystem而不是特定于操作系统的命令。你会用 C++17 吗? -
感谢 AndyG - 不幸的是,我使用的是旧版本,无法升级
-
@Poe
std::filesystem自 C++11 起为experimental,它与 C++17 中的“完整”版本(除了一两个例外)相同 -
文件不在您的控制范围内。这意味着,使用有损字符编码(就像你一样)会在某些时候引起问题。您需要使用适用于所有情况的字符编码。在 Windows 上是 UTF-16LE,
wchar_t可以使用任何 Windows 编译器进行编码。
标签: c++ winapi search directory find