何时在Go中刷新文件?

huangapple go评论81阅读模式
英文:

When to flush a file in Go?

问题

什么时候需要刷新文件?我从来不这样做,因为我调用了File.Close,我认为它会自动刷新,不是吗?

英文:

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

答案1

得分: 30

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

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

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

你不需要调用.Sync()方法。

英文:

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()

答案2

得分: 26

请参阅这里File.Sync()是对fsync的系统调用。您可以在该名称下找到更多信息。

请记住,fsyncfflush不同,并且不会在关闭之前执行。

通常情况下,您不需要调用它。文件将在一段时间后写入磁盘,如果在此期间没有停电。

英文:

See here. File.Sync() is syscall to fsync. You should be able to find more under that name.

Keep in mind that fsync is not the same as fflush and is not executed before close.

You generally don't need to call it. The file will be written to disk anyway, after some time and if there is no power failure during this period.

答案3

得分: 4

这里大部分的建议是不要调用fsync(),但总的来说,这主要取决于你的应用需求。如果你正在处理关键的文件读写操作,建议始终调用fsync()。

链接http://www.microhowto.info/howto/atomically_rewrite_the_content_of_a_file.html#idp31936中有更多关于何时调用file.Sync()会有帮助的详细信息。

英文:

Looks the most recommendations here are to not to call fsync(), but in general it mainly depends on your application requirement. If you are working on critical file read/write, its always recommended to call fsync().

http://www.microhowto.info/howto/atomically_rewrite_the_content_of_a_file.html#idp31936

link, has more details on when file.Sync() will help.

答案4

得分: 0

当您希望尽可能确保数据完整性时。例如,如果您的程序在关闭文件之前崩溃会发生什么?

英文:

When you want to ensure data integrity as much as possible. For example, what happens if your program crashes before it comes to closing the file?

huangapple
  • 本文由 发表于 2012年6月2日 20:37:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/10862375.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定