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 is the same every time.
-
4Couple things: first of all, please mention (and tag) your platform (Windows, Mac, iOS, etc etc)-- file operations are often platform dependent. Secondly, please say more about your workflow here, and whether you're creating the file, or how you would conceptually search for it, etc. – Ben Zotto Feb 25 '11 at 22:50
4 Answers
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.
- 476,176
- 80
- 629
- 1,111
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;
}
- 21,501
- 8
- 58
- 94
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
- 5,970
- 4
- 28
- 37
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.
- 1
- 1
- 7,627
- 1
- 22
- 27