开发者

How do i open a file when you know only part of the file name? C++

I need to be able to open a file when i only know part of the file name. i know the extension but the filename is different every time it is created, but the first part i开发者_开发技巧s the same every time.


You'll (probably) need to write some code to search for files that fit the known pattern. If you want to do that on Windows, you'd use FindFirstFile, FindNextFile, and FindClose. On a Unix-like system, opendir, readdir, and closedir.

Alternatively, you might want to consider using Boost FileSystem to do the job a bit more portably.


On a Unix-like system you could use 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;
}


Use Boost.Filesystem to get all files in the directory and then apply a regex (tr1 or Boost.Regex) to match your file name.

Some code for Windows using Boost.Filesystem V2 with a recursive iterator :

#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


I think you must get list of files in a directory - this [link] will help you with it. After that, I think will be quite easy to get a specific file name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜