C ++ file I / O opens two files at once

Is it impossible to open two files at the same time using different streams? What I am trying to write in two streams has a variable file name that changes every time the iteration loop and the other has a fixed file name, and the data that I write should be added at each 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 was not even able to get the second file to be created, not to mention opening and adding. I can send the full code (this is about 1000 lines or so, I need to truncate it), but I thought that the above explains what I'm trying to do, and any logical flaws will be obvious to professionals.

Thanks for all the suggestions!

+4
source share
2 answers

You make it a lot harder than it is. As a rule, there is no need to use the .open () and .close () methods, and you do not need to open 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"; } } 
+3
source

I would turn the entered code 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 run into any problems along the way, this code is simple enough to help narrow down the issue.

+1
source

All Articles