Skip to content

c++ - writing to a output file from diffrent cpp files

An answer to this question on Stack Overflow.

Question

We have three diffrenet .cpp files. when i make a file in random.cpp

ofstream outfile ("random.log");

Then I write to the file random.log in the random.cpp file:

outfile << " something" ;

Then i go to a diffrent .cpp file like StudentCS.cpp there I open the file using:

ofstream outfile;
    outfile.open("random.log",std::ios_base::app);

It will write all of the StudentCS output after all of the random.cpp output even if I call StudentCS in the middle of random.cpp. I am trying to wrtie from random.cpp then it calls StudentCS.cpp which should write something then back to random.cpp which writes again

Answer

I see that you are using the name "random.log".

Does this imply that you are writing a log file? If so, you could consider using one of many logging classes developed to make this process easier (see 1, 2, 3, 4, 5).

Another thought...

You are opening and closing your file in different parts of the project. Other answers have suggested passing a file pointer around. But if you really need to write to this file from everywhere and take the proper precautions, you could consider using a global variable here.