tags:

views:

61

answers:

3

My function takes an array of ifstream ofjects and the number of ifstream objects as seen below:

void MergeAndDisplay(ifstream files[], size_t count)

My problem is I want to use a while loop to read from the file(s) as long as one of them is open. When I get to eof, I close the file. So I thought I could do something like

int fileNum = 0;
while(files[fileNum].is_open() || something here) {
//do stuff
}

But I am not really sure how to put the correct amount of parameters in my while loop...

+2  A: 

You will have to compute the logic of "is any file in this set open" separately. I suggest making it its own function so that the while loop can be clean and natural, e.g.

bool isAnyOpen(ifstream files[], size_t count) {
  for (size_t i = 0; i < count; ++i) {
    if (files[i].is_open()) return true;
  }
  return false;
}

Then you can write

while(isAnyOpen(files, count)) {
  // Your code here
}

Edit: This is a more general case solution than what R Samuel Klatchko posted. If your problem is as simple as wanting to just read all the data out of all the files, then use his method since it is more direct.

Tyler McHenry
A: 

You probably want

while (fileNum < count && files[fileNum].is_open())

with the condition that you increment fileNum whenever you open a new file in your loop.

Alok
A: 

Try something like this:

void ProcessStream(std::istream& input_file)
{
//...
}

// Your loop
bool  a_file_is_open = true;
do
{
  a_file_is_open = false;
  for (unsigned int i = 0; i < MAX_FILES; ++i)
  {
    if (files[i].is_open())
    {
      a_file_is_open = true;
      ProcessStream(files[i]);
      break;
    }
  }
} while (a_file_is_open);
Thomas Matthews