Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

problem with ofstream

Status
Not open for further replies.

benaam

Programmer
Jan 11, 2001
20
US
I have got a strange problem.I have the following code:
I have a static method in X.cpp which is as follows:

void X::log() {
if(fs.is_open() == 0) {
fs.open("log.txt",ios::app);
fs<<&quot;hello&quot;;
} else
fs<<&quot;hello&quot;;
}
}

I declare the fs(ofstream) as static in the following way in X.cpp:
ofstream X::fs;

Now I call this method 100 times from Y.cpp in the following fashion:

#include &quot;X.cpp&quot;

void main() {
for(int i=0;i<100;i++) {
X::log();
}
}

As the ofstream object fs is a static variable it should open log.txt for the first time and should
always point to log.txt. But it is writing to the file log.txt only once. What can be the reason?

Thanx in Advance,
 
Just glancing at your code, are you flushing your write buffers? For example:
Code:
fs << &quot;Hello&quot; << flush; // flushes the buffer
fs << &quot;Hello&quot; << endl; // sends nl/cr or nl and then flushes the buffer

Also make certain that you are closing your file. This flushes the buffer, too.

James P. Cottingham
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top