2013-03-09 32 views
3

在我的項目中,我需要用文本行顯示用文件名過濾的用戶驅動器上的所有文件。有沒有API來做這種事情?Linux上的文件搜索API

在Windows上,我知道在WinAPI中有FindFirstFile和FindNextFile函數。

我使用C++/Qt。

+1

[查看](http://en.wikipedia.org/wiki/Find)? – tjameson 2013-03-09 11:06:51

+0

@tjameson這是命令行實用程序,我對C++函數感興趣 – 2013-03-09 11:11:02

+0

我的意思是你可以掏空。你可以使用[Boost](http://www.boost.org/doc/libs/1_36_0/libs/filesystem/doc/index.htm)嗎? – tjameson 2013-03-09 11:15:10

回答

3

Qt提供了QDirIterator類:

QDirIterator iter("/", QDirIterator::Subdirectories); 
while (iter.hasNext()) { 
    QString current = iter.next(); 
    // Do something with 'current'... 
} 
+0

它足夠快嗎?例如,使用模式'*'中問題中提到的WinAPI函數大約需要3秒才能找到約32000個文件。我不太確定Qt的工作如此之快。 – 2013-03-09 11:16:27

+1

@gxoptg這些函數與底層操作系統或文件系統一樣快或慢。通過使用不同的函數來完成這一點,你幾乎沒有什麼可以加速的。 – nos 2013-03-09 11:17:46

+0

檢查它,運行速度比winapi版本o.O – 2013-03-09 11:29:06

4

ftw()和Linux有fts()

除了這些,你可以遍歷目錄,例如使用opendir8/readdir()

2

如果你正在尋找一個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; 
     } 
0

man findfind通過掩模(-name選項examole)