In my project, i generate a logfile (text file) to write the intermediate results.
i use statement as a global declaration of an object of ofstream.
ofstream outLog;
then in the class constructor i use
outLog.open(outLogFname.c_str(),ios::app);
and in the destructor i close the file.
outLog.close();
I use outLog<<"....."; statement to write the log within all class functions.
Unfortunately it create the particular class but file remains empty.
Due to the long code i can not past the whole implementation.
I need your guidance that what is best way to declare/open a file which should be available for all class functions rather than opening and closing a file in each function.
#include <fstream>
std::ofstream file;
struct S{
S(){ file.open("log.txt"); }
~S(){ file.close(); }
};
int main (){
S s0;
file << "hello";
return 0 ;
}
works fine.
Now, declare another object s1 on line 11. That does not work. Because if you gave two objects, you call two constructors and thus open the file twice, which makes no sense.
You could fix this by adding if(!file.is_open()) to the constructor or file.clear() before output, but those are hacks.
What you need to do is fix the structure of your program. Log file is not in any way related to a single object, so it shouldn't be dealt with in the constructor/destructor of that object (if it is, then file should be a member of the object). Open and close file in main. For cleanness you could write a Log class.
When you said you want "...a file which should be available for all class functions..." do you remember to declare an instance of the object itself in the global scope?
Anyway, when you are making a log file you generally want to use one function that takes a string or array of strings (your style choice) as an argument and open + closes the file with in it's own scope. I can't think of a reason to create an object unless it will be doing more then fstream already does.