Writing Files
This Go code demonstrates writing to files using various methods from the os
and bufio
packages. Let's go through the code with inline comments and explanations:
Output
Explanation:
Writing to Files:
os.WriteFile("/tmp/dat1", d1, 0644)
writes the byte sliced1
to a file named "dat1".os.Create("/tmp/dat2")
creates a new file or truncates an existing one.
Writing Bytes and Strings:
f.Write(d2)
writes the byte sliced2
to the file.f.WriteString("writes\n")
writes the string "writes" to the file.
Flushing and Syncing:
f.Sync()
ensures that all changes to the file are flushed to disk.
Buffered Writing:
bufio.NewWriter(f)
creates a buffered writer for efficient writing.w.WriteString("buffered\n")
writes the string "buffered" using the buffered writer.w.Flush()
ensures that all data buffered in the writer is written to the file.
This code demonstrates different methods for writing data to files in Go, including direct writing, buffered writing, and flushing changes to disk.
Last updated
Was this helpful?