I can append anything new at the end of file in Golang like this
f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
panic(err)
}
defer f.Close()
if _, err = f.WriteString(text); err != nil {
panic(err)
}
But how can I append something in the middle of a file or after some particular line or text?
On disk, a file (a sequence of bytes) is stored similarly to an array.
Thus, appending to the middle of the file requires shifting the bytes after the point that you write to.
Then, suppose you have an index idx
where you want to append, and some bytes b
to write. The simplest (but not necessarily most efficient) way to append in the middle of a file would involve reading the file at f[idx:]
, writing b
to f[idx:idx+len(b)]
, and then writing the bytes that you read in the first step:
// idx is the index you want to write to, b is the bytes you want to write
// warning from https://godoc.org/os#File.Seek:
// "The behavior of Seek on a file opened with O_APPEND is not specified."
// so you should not pass O_APPEND when you are using the file this way
if _, err := f.Seek(idx, 0); err != nil {
panic(err)
}
remainder, err := ioutil.ReadAll(f)
if err != nil {
panic(err)
}
f.Seek(idx, 0)
f.Write(b)
f.Write(remainder)
Depending on what you're doing, it may make more sense to read the file line by line and write adjusted lines to a new file, and then rename the new file to the old filename.