在 Golang 中的文件之间追加



我可以像这样在 Golang 的文件末尾附加任何新内容

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

但是,如何在文件中间或某些特定行或文本之后附加某些内容?

在磁盘上,文件(字节序列(的存储类似于数组。

因此,追加到文件中间需要将字节移到写入点之后。

然后,假设您有一个要追加的索引idx,以及一些b要写入的字节。在文件中间追加的最简单(但不一定是最有效的(方法是在f[idx:]读取文件,将b写入f[idx:idx+len(b)],然后写入您在第一步中读取的字节:

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

根据您正在执行的操作,逐行读取文件并将调整后的行写入新文件,然后将新文件重命名为旧文件名可能更有意义。

最新更新