Search code examples
gobuffer

Writing buffer to file doesn't return error, so why is file empty afterwords?


I'm trying to read all standard input and write it to a file. It's writing nothing to the file provided. Why is it not working?

package main

import (
    "os"
    "bytes"
    "fmt"
    "bufio"
)

func main() {
    fn := os.Args[1]
    var input bytes.Buffer
    scanner := bufio.NewScanner(os.Stdin)

    for scanner.Scan() {
        fmt.Fprintf(&input, scanner.Text())
        fmt.Fprintf(&input, "\n")
    }   

    fi, _ := os.Open(fn)
    defer fi.Close()

    fi.Write(input.Bytes())
}

And then...

touch writetothis.txt
echo "input text" | go run main.go writetothis.txt
# writetothis.txt is empty

Solution

  • Open opens a file in read-only mode.
    Refer to documentation: https://golang.org/pkg/os/#Open

    Instead, use OpenFile.

    Also, always check for errors whenever you code. It'll save you at least weeks of work-hours in your lifetime.

    Here is a working code:

    package main
    
    import (
        "bufio"
        "bytes"
        "fmt"
        "os"
    )
    
    func main() {
        fn := os.Args[1]
        var input bytes.Buffer
        scanner := bufio.NewScanner(os.Stdin)
    
        for scanner.Scan() {
            fmt.Fprintf(&input, scanner.Text())
            fmt.Fprintf(&input, "\n")
        }
    
        fmt.Println(input.Bytes())
        fi, err := os.OpenFile(fn, os.O_RDWR|os.O_CREATE, 0755)
    
        if err != nil {
            fmt.Println("Error with Open()",err)
        }
        defer fi.Close()
    
        n, err := fi.Write(input.Bytes())
        if err != nil {
            fmt.Println("Error with Write()", err)
        }
        fmt.Println("Bytes written to file: ",n)
    }