Writing files

suggest change

Write the whole file

The simplest way to write data to a file:

d := []byte("content of the file")
err := os.WriteFile("foo.txt", d, 0644)
if err != nil {
    log.Fatalf("os.WriteFile failed with '%s'\n", err)
}

Open file for writing

f, err := os.Create("foo.txt")
if err != nil {
    log.Fatalf("os.Create failed with '%s'\n", err)
}

Create returns *os.File, which implements io.Writer and io.Closer.

If the file doesn’t exist, it is created.

If the file does exist, it is truncated.

Close files so you do not leak file descriptors.

Close can return an error. Check it: writes may be buffered, and Close may flush the remaining bytes.

Writes can be buffered and Close might need to flush remaining cached bytes to disk. That might fail and return an error.

Open file for appending

f, err := os.OpenFile(filePath, os.O_WRONLY | os.O_APPEND | os.O_CREATE, 0666)
if err != nil {
    log.Fatalf("os.OpenFile failed with '%s'\n", err)
}

The second argument to os.OpenFile is a flag that determines how the file is opened.

When you open for reading, use os.Open.

When you open for writing to a new file, use os.Create.

When you open for appending to an existing file, use os.OpenFile with these flags:

Write to a file

d := []byte("data to write")
nWritten, err := f.Write(d)

File permissions when creating files

When you create a new file with os.Create or os.OpenFile, you need to provide file permissions for the new file.

For most cases 0644 is a good choice.

Those are Unix-style permissions in octal. On Unix, the process umask may clear some of these bits, so the mode stored on disk can be narrower than the value you pass.

Let’s deconstruct parts of 0644

Those permissions are native to Unix and macOS, and they map loosely onto Windows.

To manage Windows permissions you need to use Windows API.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents