File I/O with C++ open two files simultaneously

12,762

Solution 1

You're making it far harder than it is. Generally there's no need to use .open() and .close() methods, and you don't need to keep reopening the same file:

#include <fstream>

int main(int argc, char *argv[])
{
    std::ofstream file_to_be_appended("fixed name");

    char const *list[] = {"a", "b", "c"};
    for (auto s : list) { // My compiler doesn't have generalized initializer lists yet
        std::ofstream file_variable_name(s);

        file_variable_name << "write something\n";
        file_to_be_appended << "write same as above, but this is to be appended\n";
    }
}

Solution 2

I would turn the code you posted into a simple program:

#include <iostream>
#include <fstream>

int main() {
  ofstream file_variable_name;
  ofstream file_to_be_appended;

  file_variable_name.open("variable_name.txt", ios::out);
  file_to_be_appended.open("fixed_name.txt", ios::out | ios::app);

  file_variable_name << "write something" << endl;
  file_to_be_appended << "write same as above, but this is to be appended" << endl;

  file_variable_name.close();
  file_to_be_appended.close();

  return 0;
}

Now edit it and add a loop with some dummy file names. If you encounter any problems along the way, this code is simple enough to help narrow down what the issue might be.

Share:
12,762
marillion
Author by

marillion

Updated on June 28, 2022

Comments

  • marillion
    marillion almost 2 years

    Isn't it possible to open two files simultaneously using different ofstreams? What I am trying to is writing to two ofstreams, one has a variable filename which changes every time the loop iterates, the other has a fixed filename and the data I am writing on is to be appended at every iteration of the loop. To demonstrate:

    ofstream file_variable_name;
    ofstream file_to_be_appended;
    
    {  //THIS IS A LOOP, variable_name changes at every iteration
    
    file_variable_name.open(variable_name.c_str(), ios::out);
    file_to_be_appended.open("fixed name", ios::out | ios::app);
    
    //Do lots of things here, make data ready to be written to file
    
    file_variable_name << "write something" << endl;
    file_to_be_appended << "write same as above, but this is to be appended" << endl;
    
    file_variable_name.close();
    file_to_be_appended.close();
    }
    

    Somehow, I could not even manage to get the second file to be created let alone opened and appended. I can send the full code (it's around 1000 lines or so, needs be truncated), as well, but I thought the above would explain what I am trying to do, and any logic flaws would be apparent to pros.

    Thanks in advance for all suggestions!