当您只知道部分文件名时,如何打开文件? C ++

时间:2011-02-25 22:46:56

标签: c++

当我只知道部分文件名时,我需要能够打开文件。我知道扩展名,但每次创建时文件名都不同,但第一部分每次都是相同的。

4 个答案:

答案 0 :(得分:4)

您(可能)需要编写一些代码来搜索符合已知模式的文件。如果您想在Windows上执行此操作,则可以使用FindFirstFileFindNextFileFindClose。在类Unix系统上,opendirreaddirclosedir

或者,您可能需要考虑使用Boost FileSystem来更轻松地完成工作。

答案 1 :(得分:0)

我认为你必须得到一个目录中的文件列表 - 这个[link]将帮助你。 之后,我认为获取特定文件名很容易。

答案 2 :(得分: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;
}

答案 3 :(得分: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 extensions // Boost.Regex

相关问题