Dear All: I have a C++ project (in Visual Studio 2008) that comprises of header.h, source_1.cpp file that contains main() and source_2.cpp file.
At certain points in the program, I need to output some intermediate results into a text file, say, “output.txt”. The thing is, I am unable to do this. That is, I am unable to output results into the same “output.txt” file from both source_1.cpp and source_2.cpp. I have been using ofstream for my write-to-file operations.
For instance, in source_1.cpp, I have said
ofstream ofile("output.txt");
and later in the code I would say,
ofile<<"Result of intermediate calculation are "<<intermediate_result<<endl;
to store the result into output.txt.
In source_2.cpp, it turns out I cannot define
extern ofstream ofile("output.txt");
(Error that same object has been defined in more than one place.)
I then tried saying in source_2.cpp
ofstream ofile_2("output.txt");//Note ofile_2 which is different from ofstream ofile in source_1.cpp
However, use of ofile_2 in source_2.cpp ends up erasing any previous output to the file written by ofile in source_1.cpp.
Should I be using something other than ofstream in order to write to the same file from two different .cpp files?
Thanks.
Best way: Pass a instance of type
ostream&to all clients which need to output the result. I recommend to resist the temptation to define a global staticostreamobjects visible to anybody…