如何刷新 TFileStream?
TFileStream 提供缓冲输出,这在大多数情况下都很好,但在某些情况下(特别是在调试期间)最好立即刷新缓冲区。 问题是,除了调用 Free 之外,我不知道有什么方法可以做到这一点,这会适得其反。
有更好的方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为 altCognito 的答案(FlushFileBuffers)可能是最好的,但这只是因为 TFileStream 本身不进行缓冲。 对于其他缓冲流,应首先查看该流是否提供 Flush 方法。 作为最后的手段,您可能可以使用 Seek(Begin) 然后 Seek(CurrentPos) 的老技巧。
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).
您使用 TWriter/TReader 还是直接使用 TFileStream 接口? TReader 和TWriter 有内部缓冲区。 但是对于普通的文件流,上面的回复已经对其进行了排序。 我个人会使用直接处理它的方法来实现我自己的流。
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.
您需要冲洗流。 尝试:
? 你看到/尝试过这个吗?
You need to flush the stream. Try:
? Did you see/try this?
这有点复杂,但实际上您可以在调用 (win32 api) CreateFile 中控制很多行为。 您可以添加
FILE_FLAG_WRITE_THROUGH
/FILE_FLAG_NO_BUFFERING
,甚至可以使用FILE_FLAG_SEQUENTIAL_SCAN
或FILE_FLAG_RANDOM_ACCESS
向缓存系统提供优化提示。 要以这种方式使用 TFileStream,我认为您需要重写 Create 来更改它获取文件句柄的方式。 FWIW,FlushFileBuffers 相当于文件上的关闭/打开。 如果您通过重复刷新执行大量活动,则会大大减慢代码速度。此处有一些文档
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 withFILE_FLAG_SEQUENTIAL_SCAN
orFILE_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