To read line by line, you'll want to use a bufio.Reader created from an
os.*File. http://weekly.golang.org/pkg/bufio/#NewReader
So, it would look something like
fin, err := os.Open("filename")
r := bufio.NewReader(fin)
l, _, err := r.ReadLine()
And then loop until you're done reading the file (err is io.EOF).
--
Scott Lawrence
Thank you very much, but a bit mistake: os.EOF not io.EOF
Don't ignore isPrefix!
--
matt kane's brain
http://hydrogenproject.com
2012/1/30 Matt Kane's Brain <mkb-...@hydrogenproject.com>:
Thanks,
2012/1/30 Peter Weinberger (温博格) <p...@google.com>:
> defer fin.Close()?
>
I'm trying to stay close to what the original program does, as others
point out you can use ioutil.ReadFile() if you don't mind reading the
whole file at once.
This is compiled against tip, so uses the go 1 convention of having
EOF in io rather than os. There might be other differences too.
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
)
const (
DefaultBufferSize = 100
)
func printLines(path string) {
fmt.Printf("[File: %s]\n", path)
fin, err := os.Open(path)
if err != nil {
fmt.Fprintf(os.Stderr, "The file %s does not exist!\n", path)
return
}
defer fin.Close()
bufReader := bufio.NewReader(fin)
bytes := make([]byte, DefaultBufferSize)
for line, isPrefix, err := bufReader.ReadLine(); err != io.EOF; line,
isPrefix, err = bufReader.ReadLine() {
bytes = append(bytes, line...)
if !isPrefix {
fmt.Printf("Lines: %s (error %v)\n", string(bytes), err)
bytes = bytes[:0]
}
}
}
func main() {
fmt.Println("Reading files...")
flag.Parse()
for _, path := range flag.Args() {
printLines(path)
}
}
Any + all comments welcome,
Cheers,
Lorenzo
--
Lorenzo Stoakes
http://www.codegrunt.co.uk