When to flush a file in Go?

Issue

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?

Solution

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

Answered By – Jesse

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.