BurakCan
BurakCan

Reputation: 29

How to append to the beginning of a file in Go?

I want to append to the beginning of a file. Don't get me wrong, I can append it but I want the last written string to be top (first line) of the file.

Upvotes: 0

Views: 3413

Answers (1)

Vorsprung
Vorsprung

Reputation: 34357

This example program "appends" to the start of the file

It makes assumptions that the file contents are lines with line endings and that nothing else is modifying the file

(and probably some other assumptions too..this is a simple example)

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

Upvotes: 1

Related Questions