何时在Go中刷新文件? [英] When to flush a file in Go?

查看:109
本文介绍了何时在Go中刷新文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

何时需要刷新到文件?

我永远不会这样做,因为我调用File.Close,我认为它会自动刷新,不是吗?

解决方案

你会注意到os.File没有.Flush(),因为它不需要缓冲。写给它的是直接系统调用来写入文件。



当程序退出时(即使它崩溃),所有打开的文件将被操作系统自动关闭并且文件系统会在您的程序退出时将修改写入磁盘(有时在程序退出后几分钟)。



调用os.File.Sync( )将调用fsync()系统调用,这将强制文件系统将其缓冲区刷新到磁盘。这将保证您的数据在磁盘上并且持续存在,即使系统断电或操作系统崩溃。



您不需要调用.Sync()

When is necessary to do flushing to a file?
I never do it because I calls to File.Close, and I think that it is flushed automatically, isn't it?

解决方案

You'll notice that an os.File doesn't have a .Flush() because it doesn't need one because it isn't buffered. Writes to it are direct syscalls to write to the file.

When your program exits(even if it crashes) all files it has open will be closed automatically by the operating system and the file system will write your changes to disk when it gets around to it (sometimes up to few minutes after your program exits).

Calling os.File.Sync() will call the fsync() syscall which will force the file system to flush it's buffers to disk. This will guarantee that your data is on disk and persistent even if the system is powered down or the operating system crashes.

You don't need to call .Sync()

这篇关于何时在Go中刷新文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆