18

TFileStream provides buffered output, which is great in most cases, but in some cases (especially during debugging) it's nice to flush the buffer immediately. Thing is, I don't know of any way to do that except calling Free, which is kind of counterproductive.

Is there a better way to do it?

Jim McKeeth
  • 38,225
  • 23
  • 120
  • 194
Mason Wheeler
  • 82,511
  • 50
  • 270
  • 477

4 Answers4

29

You need to flush the stream. Try:

 FlushFileBuffers(fs.Handle); 

? Did you see/try this?

cgp
  • 41,026
  • 12
  • 101
  • 131
6

I think altCognito's answer (FlushFileBuffers) is probably the best, but only because TFileStream does no buffering by itself. For other, buffered, streams should first look if the stream offers a Flush method. And as a last resort you could probably use the old trick of Seek(Begin) and then Seek(CurrentPos).

H H
  • 263,252
  • 30
  • 330
  • 514
6

It's a bit involved, but you can actually control a lot of that behavior in the call to (win32 api) CreateFile. You can add FILE_FLAG_WRITE_THROUGH / FILE_FLAG_NO_BUFFERING or even provide optimization hints to the cache system with FILE_FLAG_SEQUENTIAL_SCAN or FILE_FLAG_RANDOM_ACCESS. To use TFileStream that way, I think you'd need to override the Create to change how it obtains the file handle. FWIW, FlushFileBuffers is equivalent to a Close/Open on the file. If you're doing a lot of activity with repeated flushes, it will slow the code down considerably.

A bit of documentation here

Marshall Fryman
  • 874
  • 6
  • 3
  • 6
    Actually, you do not need to override constructor. There already is an overloaded version, which accepts a file handle. So, you must proceed as follows (error handling removed): FS := TFileStream.Create( CreateFile( PChar(FileName), ... , FILE_FLAG_WRITE_THROUGH, ... ) ); That's all. Really simple. – Alex Apr 25 '09 at 06:46
2

Are you using a TWriter/TReader or just going straight for the TFileStream interface? TReader and TWriter have internal buffers. But for a normal filestream then the replies above have it sorted. I personally would implement my own stream with methods to deal with it directly.

Jon Lennart Aasenden
  • 3,920
  • 2
  • 29
  • 44