I haven't been able to find this anywhere (or I just don't understand it). I'm reading in a list of numbers from a file separated by spaces. I.e. the file looks like "1 4 0 0 2 5 ...etc", and I want it in the form of an array (or, preferably, a 2 dimensional array where each new line is separated as well). How might I go about doing this?
This is the code I have so far - a lot of it is taken from tutorials I found, so I don't fully understand all of it. It reads in a file just fine, and returns a string. Side question: when I print the string, I get this at the end of the output: %!(EXTRA ) Does anyone know how to fix that? I'm assuming it's putting the last nil character in the return string, but I don't know how to fix that.
package main
import (
"fmt"
"os"
)
func read_file(filename string) (string, os.Error) {
f, err := os.Open(filename)
if err != nil {
return "", err
}
defer f.Close() // f.Close will run when we're finished.
var result []byte
buf := make([]byte, 100)
for {
n, err := f.Read(buf[0:])
result = append(result, buf[0:n]...) // append is discussed later.
if err != nil {
if err == os.EOF {
break
}
return "", err // f will be closed if we return here.
}
}
return string(result), nil // f will be closed if we return here.
}
func print_board() {
}
func main() {
fmt.Printf(read_file("sudoku1.txt")) // this outputs the file exactly,
// but with %!(EXTRA <nil>) at the end.
// I do not know why exactly
}
Thank you very much for any help you can offer.
-W