我想附加到文件的开头。不要误会我的意思,我可以附加它,但是我希望最后写入的字符串在文件的顶部(第一行)。
最佳答案
此示例程序“追加”到文件的开头
它假设文件内容是带有行尾的行,并且
没有其他东西正在修改文件
(可能还有其他一些假设。.这是一个简单的示例)
package main
import (
"bufio"
"os"
)
func main() {
addline := "aaa first\n"
// make a temporary outfile
outfile, err := os.Create("newfoo.txt")
if err != nil {
panic(err)
}
defer outfile.Close()
// open the file to be appended to for read
f, err := os.Open("foo.txt")
if err != nil {
panic(err)
}
defer f.Close()
// append at the start
_, err = outfile.WriteString(addline)
if err != nil {
panic(err)
}
scanner := bufio.NewScanner(f)
// read the file to be appended to and output all of it
for scanner.Scan() {
_, err = outfile.WriteString(scanner.Text())
_, err = outfile.WriteString("\n")
}
if err := scanner.Err(); err != nil {
panic(err)
}
// ensure all lines are written
outfile.Sync()
// over write the old file with the new one
err = os.Rename("newfoo.txt", "foo.txt")
if err != nil {
panic(err)
}
}
关于file - 如何在Go中附加到文件的开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63969610/