我可以像这样在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)

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

关于file - 在Golang中的文件之间附加,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52398388/

10-16 21:21