2011-02-25 59 views
0

我需要能夠打開一個文件,當我只知道文件名的一部分。我知道擴展名,但每次創建文件名都不相同,但第一部分每次都是一樣的。當您只知道部分文件名時,如何打開文件? C++

+4

兩件事情:首先,請註明(和標籤)平臺(Windows,Mac,iOS等) - 文件操作通常取決於平臺。其次,請在此處詳細說明您的工作流程,以及您是在創建文件,還是在概念上如何搜索文件等。 – 2011-02-25 22:50:58

回答

4

您將(可能)需要編寫一些代碼來搜索符合已知模式的文件。如果您想在Windows上執行此操作,您可以使用FindFirstFile,FindNextFileFindClose。在類Unix系統上,opendir,readdirclosedir

或者,您可能需要考慮使用Boost FileSystem以更便攜的方式完成這項工作。

+0

+1用於Boost FileSystem。 – 2011-02-25 23:07:38

0

我認爲你必須得到一個目錄中的文件列表 - 這[link]將幫助你。之後,我認爲將很容易得到一個特定的文件名。

0

在類Unix系統上,您可以使用glob()

#include <glob.h> 
#include <iostream> 

#define PREFIX "foo" 
#define EXTENSION "txt" 

int main() { 
    glob_t globbuf; 

    glob(PREFIX "*." EXTENSION, 0, NULL, &globbuf); 
    for (std::size_t i = 0; i < globbuf.gl_pathc; ++i) { 
     std::cout << "found: " << globbuf.gl_pathv[i] << '\n'; 
     // ... 
    } 
    return 0; 
} 
0

使用Boost.Filesystem獲得目錄中的所有文件,然後應用正則表達式(或TR1 Boost.Regex)來匹配您的文件名。

使用Boost.Filesystem的V2用遞歸迭代器Windows中的某些代碼:

#include <string> 
#include <regex> 
#include <boost/filesystem.hpp> 
... 
... 
std::wstring parent_directory(L"C:\\test"); 
std::tr1::wregex rx(L".*"); 

boost::filesystem::wpath parent_path(parent_directory); 
if (!boost::filesystem::exists(parent_path)) 
    return false; 

boost::filesystem::wrecursive_directory_iterator end_itr; 
for (boost::filesystem::wrecursive_directory_iterator itr(parent_path); 
    itr != end_itr; 
    ++itr) 
{ 
    if(is_regular_file(itr->status())) 
    { 
     if(std::tr1::regex_match(itr->path().file_string(),rx)) 
      // Bingo, regex matched. Do something... 
    } 
} 

Directory iteration with Boost.Filesystem. // // Getting started with regular expressions using C++ TR1 extensionsBoost.Regex

相關問題