Writing files
suggest changeWrite 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:
os.O_WRONLY, oros.O_RDWRif you also need to reados.O_APPENDso that writes go at the end when the file already existsos.O_CREATEso that a missing file is created. Without this flag, opening a missing file fails
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
0means this is a number in octal format. That means that each number is in 0-7 range (compare to regular decimal notation where each number is in 0-9 range)- 6 is permissions for the creator of the file. It’s a bitmask 4 + 2. 4 means read permissions, 2 means write permission. When combined it means read/write access
- 4 is permissions for the group that user belongs to. I.e. every user that also belongs to the same group will have those permissions. 4 means only read permissions
- last 4 is for everyone. Again, 4 means only read permissions
- for completeness, 1 represents executable permissions so if this is meant to be an executable file, the permissions flag would be
0755i.e. for each user/group/anonymous component we add 1 to set executable bit
Those permissions are native to Unix and macOS, and they map loosely onto Windows.
To manage Windows permissions you need to use Windows API.