C++ File I/O quick question

M

Mark

Hi,
I have an app that uses a log file to log certain events. It writes to the
log file a few times per minute. Is it preferable to open the file when the
program starts and close it when it finishes? Or to open-write-close for
every new entry in the log? Is there any difference between these two
techniques (besides the flushing on close)?

Thanks,
Mark
 
K

Kevin Goodsell

Mark said:
Hi,
I have an app that uses a log file to log certain events. It writes to the
log file a few times per minute. Is it preferable to open the file when the
program starts and close it when it finishes? Or to open-write-close for
every new entry in the log? Is there any difference between these two
techniques (besides the flushing on close)?

There's probably some overhead for each open and close other than the
flushing, but how much difference this makes will depend heavily on your
implementation.

I'd say the answer depends on what purpose the log serves and exactly
how your implementation's file system works. Assume your program never
exits unexpectedly, and the log is never accessed from outside your
program while your program is running. In that case, it doesn't matter
which you choose, because the observable result is identical.

Now, you might want a log to help diagnose errors in your program. In
that case, it's important that any data you write makes it to permanent
storage as soon as possible (in case something goes wrong - you don't
want to lose any data). Closing the file after writing should give you a
high degree of confidence that this will be the case. But it's probably
not necessary - flushing the stream (or disabling buffering altogether)
is probably good enough. However, this depends on your implementation.

-Kevin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,159
Messages
2,570,879
Members
47,416
Latest member
LionelQ387

Latest Threads

Top