When to flush a file in Go?

前端 未结 4 1027
离开以前
离开以前 2021-02-07 06:35

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?

4条回答
  •  無奈伤痛
    2021-02-07 07:27

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

提交回复
热议问题