I have a bunch of text files in a directory, and each text file is named "info1.txt", "info2.txt" and so on. How would I open up all of the text files in an array of ifstream objects without having to hard-code all my text file names in? I know the following code does not work, but I think it conveys the idea of what I want to do if it did work:
ifstream myFiles[5];
for(int i = 0; i < 5; i++){
myFiles[i].open("info" + i + ".txt");
}
I know the solution is probably very simple, but after a lot of research, trial and error I still haven't figured it out. Thanks!
Your idea should work with a small change:
Also note that, you cannot use
std::vector
becauseifstream
is not a copyable object. So continue using the array.I usually use std::stringstream:
For building the file names, I'd use
std::ostringstream
andoperator<<
.If you want to use a container class like
std::vector
(e.g. because you don't know at compile time how much big the array ofifstream
's will be), sincestd::ifstream
is not copyable, you can't usevector<ifstream>
, but you can usevector<shared_ptr<ifstream>>
orvector<unique_ptr<ifstream>>
; e.g.:With
unique_ptr
(and C++11 move semantics):unqiue_ptr
is more efficient thanshared_ptr
, sinceunique_ptr
is just a movable pointer, it's not reference counted (so there is less overhead thanshared_ptr
). So, in C++11, you may want to preferunique_ptr
if theifstream
's are not shared outside thevector
container.You can have an array of ifstream objects, but if you need a dynamic length, then you cannot do it this way, nor will
std::vector<ifstream>
work.So you will need pointers.
std::vector<ifstream*>
will work but you might use shared_ptr sostd::vector<shared_ptr<ifstream> >
will work. If you haveunique_ptr
available you can use that instead ofshared_ptr
.Each element will then have to be created with
new
.You will also need to create the string properly, you can use a
boost::format
orostringstream
or even an old-fashionedsprintf
to do that.By the way, I would search boost's filesystem library to see if they have a more dynamic
ifstream
that can go happily in your vector without the messiness of shared_ptr.The problem is, I guess, the part about dynamically creating the file name.
One of the simple solutions is to use
std::ostringstream
to do it:If your library is to old for it to accept
std::string
arguments in the call toopen
then use