terryp
terryp

Reputation: 249

GoLang: Reading a File Basics

I'm just trying to read a simple file that's in the same directory as the actual program. I keep getting this odd error and my Go is "emerging" (as they say).

package main

import (
    "bufio"
    "fmt"
    "io/ioutil"
    "os"
    "path/filepath"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func main() {
    // Here's opening a flat file via the program.
    // fn := " ... /foo.txt"
    here, err := filepath.Abs(".")
    check(err)

    fmt.Println("------- DEBUG ------- ")
    fmt.Println(here)
    fmt.Println("------- DEBUG ------- ")

    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Please Enter a File Name: ")

    f, err := reader.ReadString('\n')
    f = filepath.Join(here, f)
    fmt.Println(f)
    check(err)

    dat, err := ioutil.ReadFile(f)
    check(err)
    fmt.Print(string(dat))
}

So here's the weird error, I keep getting.

panic: open ... /foo.txt
: no such file or directory

goroutine 1 [running]:
main.check(0x22081c49a0, 0x2081ec240)
... /read.go:13 +0x50
main.main()
... /read.go:36 +0x6b0
exit status 2

When I just use the static name and not standard in, it works fine. There must be something odd with the way standard in pulls in that string and then tries to turn it into a file path.

Upvotes: 1

Views: 256

Answers (1)

Rob Napier
Rob Napier

Reputation: 299265

f, err := reader.ReadString('\n')

This reads up-to-and-including the \n. So your filename is /foo.txt\n which doesn't exist.

You can use strings.Trim() to pull off the newline if you like.

Upvotes: 7

Related Questions