Hi
I am trying to learn c++ by using it where I can at work. Usually I can muddle through by searching forums and although I might not end up with an elegant piece of code, my programs seem to work ;)

What I am trying to do, is open multiple files so they can be processed simultaneously. Each file name is the same but they are in sequentially numbered directories. The command line accepts arguments for the path to the directory that contains the numbered directories, the name of the files, and the number of files to expect.

Currently, I have code that will open one file after another. Is there a way to use an array to store the file handles? Or something more clever?

Thanks for any help!

#include <fstream>
#include <iostream>
#include <sstream>

using namespace std;

int main(int argc, char **argv) {
 if (argc < 4) {
   exit(1);
 }


 string path = argv[1];
 string file = argv[2];
 int num =  atoi(argv[3]);


 for(int i=0; i<num; i++) {

   std::ifstream(infile);
   infile.seekg(0,ios::beg);
   std::stringstream num_str;
   num_str << i + 1;
   string filename = path + "/dir" + num_str.str() + "/" + file;

   infile.open( filename.c_str(), ios::in );

   if(!(infile)) {
     cout << "opening " << filename << " failed" << endl;
     exit(1);
   }
   else {
     cout << filename << " opened" << endl;
   }
 }

// do something with each open file then close them all

 return 0;
}

line 21: you can delete it because the file pointer is already at the beginning of the file when it is opened.

line 26: you don't need the ios::in flag because ifstream is an input stream. All you need is infile.open( filename.c_str()); >>Is there a way to use an array to store the file handles?
Yes. One way to do it is like this:

ifstream* array = new ifstream[num];
...
 for(int i=0; i<num; i++) {
   std::stringstream num_str;
   num_str << i + 1;
   string filename = path + "/dir" + num_str.str() + "/" + file;

   array[i]->open(filename.c_str());

   if(!(array[i])) {
     cout << "opening " << filename << " failed" << endl;
     exit(1);
   }
   else {
     cout << filename << " opened" << endl;
   }
 }

Thanks Ancient Dragon!

That's exactly what I was looking for.

Cheers

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.