1

In python, if you want to open all the files that started with "apl_" you can simply open "apl*". How do you do something similar in C++.

Say I have a file which I know starts with "llll", but have unknown suffixes. How do I open it?

  • 1
    It might not be the best way, but one method could be to iterate through them with `boost::filesystem`, check if `name.find ("llll") == name.begin()`, and open the ones that satisfy the condition. – chris Jul 13 '12 at 00:23
  • 1
    No, you can't do that in Python. Of course there are other ways to do it—but open("api*") will raise an IOError (unless you actually have a file called "api*") – abarnert Jul 13 '12 at 00:25
  • 1
    @abarnert: Check out the `glob.glob()` function: `open(glob.glob('apl_*')[0], 'r')` – Blender Jul 13 '12 at 00:26
  • @Blender: Yes, but that's not the same as "simply opening". You can also call _glob or FindFirstFile/FindNextFile from C or C++ on Windows, which is the nearest equivalent to glob.glob in Python. – abarnert Jul 13 '12 at 00:28
  • @abarnert: Post that as an answer ;) That's what the OP is trying to do. – Blender Jul 13 '12 at 00:29
  • Actually, I'm not sure that's what the OP is trying to do. I suspect he's actually calling his Python script with api* on the command line and cmd is expanding it for him, in which case the exact same thing will work in C++… – abarnert Jul 13 '12 at 00:33

2 Answers2

2
  1. Open the directory
  2. Step through the list of files in the directory
  3. Open the files whose names match your pattern.

C: How to obtain a list of files in Windows directory?

Community
  • 1
  • 1
tylerl
  • 30,197
  • 13
  • 80
  • 113
2

You cannot just 'simply open "apl*"' in Python. If you try this:

open("apl*")

You will get an IOError—unless you happen to have a file literally named "apl*".

There are two basic ways to do this in Python, both of which can be translated to C++.

First:

[open(f) for f in glob.glob("apl*")]

On most non-Windows platforms, glob.glob translates directly into the POSIX function glob. Unfortunately, on Windows, it's called _glob, doesn't exist on all versions of Windows, and has severe limitations. So, instead, you want to use FindFirstFile and FindNextFile. The examples given on the linked pages should show you how to do it.

Second:

[open(f) for f in os.listdir(".") if f.startswith("apl")]

You can again do this by just using FindFirstFile/FindNextFile to iterate the entire directory, and then filter on whether data->cFileName starts with "apl", but you might as well use much cleaner (and more portable) boost::filesystem::directory_iterator.

abarnert
  • 354,177
  • 51
  • 601
  • 671