The simplest method of reading a text file?

4,074 views
Skip to first unread message

Xavier

unread,
Jan 29, 2012, 2:01:24 PM1/29/12
to golang-nuts
Hi,

Anyone could say me what is the simplest method to read a text file? I
don't get it in os pkg examples!

I want to read line by line.


Thanks in advance,
Xan.

PS: Please CCme

Scott Lawrence

unread,
Jan 29, 2012, 6:31:07 PM1/29/12
to Xavier, golang-nuts
ioutil.ReadFile will read the whole file into []byte for you:
http://tip.golang.org/pkg/io/ioutil/#ReadFile

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

signature.asc

Xavier

unread,
Jan 30, 2012, 1:33:46 PM1/30/12
to golang-nuts
Thank you very much, but a bit mistake: os.EOF not io.EOF

I return the code to the community:

package main

import (
"flag"
"fmt"
"os"
"bufio"
)

func main() {
fmt.Printf("Reading files...\n");
flag.Parse();

for i :=0; i < flag.NArg(); i++ {
fmt.Printf("[File: %v]\n", flag.Arg(i));
fin, err := os.Open(flag.Arg(i))
if (err==nil) {
r := bufio.NewReader(fin)
for line, _, err := r.ReadLine(); err!=os.EOF; line, _, err =
r.ReadLine() {
fmt.Printf("Lines: %v (error %v)\n", string(line), err)
}
} else {
fmt.Printf("The file %v does not exist!\n", flag.Arg(i))
}
}
}


This reads all the lines of files passed as arguments.

Can we improve it?

Thanks,
Xan.

On Jan 30, 12:31 am, Scott Lawrence <byt...@gmail.com> wrote:
> ioutil.ReadFile will read the whole file into []byte for you:http://tip.golang.org/pkg/io/ioutil/#ReadFile
>
> 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
>
>  signature.asc
> < 1KViewDownload

Andy Balholm

unread,
Jan 30, 2012, 3:02:47 PM1/30/12
to golan...@googlegroups.com
Thank you very much, but a bit mistake: os.EOF not io.EOF 
 
In recent versions of Go, EOF has been moved to the io package.

unread,
Jan 30, 2012, 3:05:36 PM1/30/12
to golang-nuts
On Jan 30, 7:33 pm, Xavier <xancor...@gmail.com> wrote:
> Thank you very much, but a bit mistake: os.EOF not io.EOF

There have been some renames since release.r60.3. In weekly.2012-01-27
it is io.EOF.

Kyle Lemons

unread,
Jan 30, 2012, 5:08:27 PM1/30/12
to Xavier, golang-nuts
If you don't mind reading in the whole file at once, you can use ioutil.ReadFile and bytes.Split. 

Matt Kane's Brain

unread,
Jan 30, 2012, 5:18:40 PM1/30/12
to Xavier, golang-nuts
On Mon, Jan 30, 2012 at 13:33, Xavier <xanc...@gmail.com> wrote:
> Can we improve it?

Don't ignore isPrefix!

--
matt kane's brain
http://hydrogenproject.com

Peter Weinberger (温博格)

unread,
Jan 30, 2012, 5:51:54 PM1/30/12
to Xavier, golang-nuts
defer fin.Close()?

Peter Weinberger (温博格)

unread,
Jan 30, 2012, 5:53:05 PM1/30/12
to Peter Weinberger (温博格), Xavier, golang-nuts
oops: close it after printing it.

Xan xan

unread,
Jan 31, 2012, 4:11:43 AM1/31/12
to Matt Kane's Brain, golang-nuts
How can I do that?

2012/1/30 Matt Kane's Brain <mkb-...@hydrogenproject.com>:

Xan xan

unread,
Jan 31, 2012, 4:12:53 AM1/31/12
to Peter Weinberger (温博格), golang-nuts
Defer?
In what line I have to insert defer fin.Close()?

Thanks,

2012/1/30 Peter Weinberger (温博格) <p...@google.com>:
> defer fin.Close()?
>

CrossWall

unread,
Jan 31, 2012, 8:12:02 AM1/31/12
to golan...@googlegroups.com, Matt Kane's Brain
ioutil.ReadFile("path_to_file")

Lorenzo Stoakes

unread,
Feb 1, 2012, 4:31:57 PM2/1/12
to golan...@googlegroups.com
Since I happen to need very similar code, I've had a crack at what I
hope is a cleaner version of the code that takes isPrefix into account
and defers closing of the file, though of course I am open to any
constructive criticism :)

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

Reply all
Reply to author
Forward
0 new messages