When to flush a file in Go?

user1243746 picture user1243746 · Jun 2, 2012 · Viewed 16.8k times · Source

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?

Answer

Jessta picture Jessta · Jun 5, 2012

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