I found the solution myself - when read in from stdin, there are 2 extra characters - CR and LF. I just cut the string 2 characters before the end, and it works! Thanks to those for posting replies!
On Thursday, August 24, 2017 at 11:35:31 PM UTC-4, Geoff Fridd wrote: > > Does anyone know why Google Go program 1 works, below, and program 2 > doesn't? The only difference - I read in the filename from the console in > the one that doesn't work but it is a literal in the one that works... I > tried typing in the full path for the file, and also "..sample.txt" instead > of "sample.txt", but they didn't solve it either. > // program 1 - this works: > > package main import ( > "fmt" > "os" > "bufio" ) > > func main() { > filename := getFilename() > fmt.Println("opening:",filename) > // fmt.Println("opening:sample.txt") > _ , err := os.Open("sample.txt") > // _ , err := os.Open(filename) > if err != nil { > panic(err) > } > } > > func getFilename() string { > reader := bufio.NewReader(os.Stdin) > fmt.Print("Enter file name: ") // type in anything, this file > name not used > filename, _ := reader.ReadString('\n') > return filename > } > > > // program 2 - this doesn't work, gives error shown below: > > package main > import ( > "fmt" > "os" > "bufio" > ) > > func main() > filename := getFilename() > fmt.Println("opening:",filename) > // fmt.Println("opening: sample.txt") > // _ , err := os.Open("sample.txt") > _ , err := os.Open(filename) > if err != nil { > panic(err) > } > } > > func getFilename() string { > reader := bufio.NewReader(os.Stdin) > fmt.Print("Enter file name: ") // type in "sample.txt" (without > the quotes) > filename, _ := reader.ReadString('\n') > return filename > } > > Error message, panic invoked - > : The filename, directory name, or volume label syntax is incorrect. > > goroutine 1 [running]: > main.main() > C:/installed programs/go/src/testopen2.go:16 +0x158 > exit status 2 > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.