在我的項目中,我需要用文本行顯示用文件名過濾的用戶驅動器上的所有文件。有沒有API來做這種事情?Linux上的文件搜索API
在Windows上,我知道在WinAPI中有FindFirstFile和FindNextFile函數。
我使用C++/Qt。
在我的項目中,我需要用文本行顯示用文件名過濾的用戶驅動器上的所有文件。有沒有API來做這種事情?Linux上的文件搜索API
在Windows上,我知道在WinAPI中有FindFirstFile和FindNextFile函數。
我使用C++/Qt。
Qt提供了QDirIterator類:
QDirIterator iter("/", QDirIterator::Subdirectories);
while (iter.hasNext()) {
QString current = iter.next();
// Do something with 'current'...
}
它足夠快嗎?例如,使用模式'*'中問題中提到的WinAPI函數大約需要3秒才能找到約32000個文件。我不太確定Qt的工作如此之快。 – 2013-03-09 11:16:27
@gxoptg這些函數與底層操作系統或文件系統一樣快或慢。通過使用不同的函數來完成這一點,你幾乎沒有什麼可以加速的。 – nos 2013-03-09 11:17:46
檢查它,運行速度比winapi版本o.O – 2013-03-09 11:29:06
如果你正在尋找一個Unix命令,你可以這樣做:
find source_dir -name 'regex'
如果你想這樣做C++風格,我建議使用boost::filesystem。這是一個非常強大的跨平臺庫。
當然,你將不得不添加一個額外的庫。
下面是一個例子:
std::vector<std::string> list_files(const std::string& root, const bool& recursive, const std::string& filter, const bool& regularFilesOnly)
{
namespace fs = boost::filesystem;
fs::path rootPath(root);
// Throw exception if path doesn't exist or isn't a directory.
if (!fs::exists(rootPath)) {
throw std::exception("rootPath does not exist");
}
if (!fs::is_directory(rootPath)) {
throw std::exception("rootPath is not a directory.");
}
// List all the files in the directory
const std::regex regexFilter(filter);
auto fileList = std::vector<std::string>();
fs::directory_iterator end_itr;
for(fs::directory_iterator it(rootPath); it != end_itr; ++it) {
std::string filepath(it->path().string());
// For a directory
if (fs::is_directory(it->status())) {
if (recursive && it->path().string() != "..") {
// List the files in the directory
auto currentDirFiles = list_files(filepath, recursive, filter, regularFilesOnly);
// Add to the end of the current vector
fileList.insert(fileList.end(), currentDirFiles.begin(), currentDirFiles.end());
}
} else if (fs::is_regular_file(it->status())) { // For a regular file
if (filter != "" && !regex_match(filepath, regexFilter)) {
continue;
}
} else {
// something else
}
if (regularFilesOnly && !fs::is_regular_file(it->status())) {
continue;
}
// Add the file or directory to the list
fileList.push_back(filepath);
}
return fileList;
}
看man find
。 find
通過掩模(-name
選項examole)
支持篩選,您還可以使用glob
http://man7.org/linux/man-pages/man3/glob.3.html 具有現有對很多Unix系統的優點(的Solaris肯定的),因爲它是POSIX的一部分。
好吧,它不是C++,但是純粹的C.
[查看](http://en.wikipedia.org/wiki/Find)? – tjameson 2013-03-09 11:06:51
@tjameson這是命令行實用程序,我對C++函數感興趣 – 2013-03-09 11:11:02
我的意思是你可以掏空。你可以使用[Boost](http://www.boost.org/doc/libs/1_36_0/libs/filesystem/doc/index.htm)嗎? – tjameson 2013-03-09 11:15:10