1

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.

1
  • Advise: Do not read input interactive from terminal. There are a lot of subtleties which will distract from the actual code. Use the command line together with package flag. Commented Aug 6, 2015 at 5:06

1 Answer 1

7
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Rob. Always the simple things that I overlook!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.