I've been trying to learn Go on my own, but I've been stumped on trying read from and write to ordinary files.
I can get as far as inFile, _ := os.Open(INFILE, 0, 0)
, but actually getting the content of the file doesn't make sense, because the read function takes a []byte
as a parameter.
func (file *File) Read(b []byte) (n int, err Error)
Best Answer
Let's make a Go 1-compatible list of all the ways to read and write files in Go.
Because file API has changed recently and most other answers don't work with Go 1. They also miss
bufio
which is important IMHO.In the following examples I copy a file by reading from it and writing to the destination file.
Start with the basics
Here I used
os.Open
andos.Create
which are convenient wrappers aroundos.OpenFile
. We usually don't need to callOpenFile
directly.Notice treating EOF.
Read
tries to fillbuf
on each call, and returnsio.EOF
as error if it reaches end of file in doing so. In this casebuf
will still hold data. Consequent calls toRead
returns zero as the number of bytes read and sameio.EOF
as error. Any other error will lead to a panic.Using
bufio
bufio
is just acting as a buffer here, because we don't have much to do with data. In most other situations (specially with text files)bufio
is very useful by giving us a nice API for reading and writing easily and flexibly, while it handles buffering behind the scenes.Note: The following code is for older Go versions (Go 1.15 and before). Things have changed. For the new way, take a look at this answer.
Using
ioutil
Easy as pie! But use it only if you're sure you're not dealing with big files.