×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

problem with ofstream

problem with ofstream

problem with ofstream

(OP)
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<<"hello";
    } else     
         fs<<"hello";
       }
}

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 "X.cpp"

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,

RE: problem with ofstream

Just glancing at your code, are you flushing your write buffers? For example:

fs << "Hello" << flush; // flushes the buffer
fs << "Hello" << 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
www.ivcusa.com

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close