登录
首页 >  Golang >  Go问答

在 Go 中如何向文件前面追加数据?

来源:stackoverflow

时间:2024-02-17 15:36:21 455浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《在 Go 中如何向文件前面追加数据?》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

问题内容

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


解决方案


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

它假设文件内容是以行结尾的行,并且 没有其他任何东西正在修改文件

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

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

以上就是《在 Go 中如何向文件前面追加数据?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>