如何在Go中附加到文件的开头?

问题描述

我想附加到文件的开头。别误会,我可以附加它,但我希望最后写入的字符串在文件的顶部(第一行)。

解决方法

该示例程序“附加”到文件的开头

它假设文件内容是带有行尾的行,并且 没有其他东西可以修改文件了

(可能还有其他一些假设。这是一个简单的示例)

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