views:

212

answers:

5

I want to write data in a file frequently ,

I wonder if I call CreateFile() each time I write it,

Does this way cost so much than the way that I just call it once ,then

use the handle many times?

+7  A: 

If you are going to write to the file several times, it would be better to keep the handle returned by CreateFile(). Creating a kernel handle to a file will always be more inefficient that reusing the old handle (all other things being equal), but there may be other considerations to take into account. As always, you should measure the performance before and after you do any such optimizations.

JesperE
Good answer. The last sentence is important.
dmeister
+1  A: 

Reusing the file handle will give you better performance and is a better design. Most likely the disk caching of the operating system will hide many of the performance hits. I am not sure why you would want to repeatedly call CreateFile() unless you are accessing it from different application areas and that makes it difficult to pass the handle along.

ojblass
+1  A: 

There is an overhead in creating handles to files and you are better off creating one handle and keeping that handle as long as you want to read/write to the file. It depends on how much you are doing this, are you doing it 100 times each second or once every minute?

Magnus Skog
+2  A: 

CreateFile will certainly take some time for each call (I'd guess microseconds if you're opening the same file again many times, thanks to driver and OS buffering, but you should measure with a little benchmark if that's crucial to you). But keeping the file open indefinitely might have unpleasant results in the case of a program or system crash in the middle of operations -- whether that's the case depends on what file format you're dealing with, and what write operations you are performing on it.

Alex Martelli
+2  A: 

Keeping the handle open is not necessarily the best approach. Keeping an open handle can be problematic, depending on your design. While CreateFile certainly has overhead, I'd be very surprised if it weren't negligible compared to the cost of the I/O operations themselves. That being said, the way to be sure is to try both ways and measure the difference. If it's negligible, as I suspect, then use whatever approach works best for you.

Peter Ruderman