This is a creation in Article, where the information may have evolved or changed.
Reading and writing files is the most basic function.
It's interesting to read in the Go language, which makes the go language different from other languages due to the interface of the go language. Like other languages, the go language has a file-type structure, but file provides only the most basic read,write functions, and features like ReadLine are Bufio in the package.
The first method, using the most traditional way, Open,read,close, is the following code:
File1.gopackage mainimport ("FMT" "OS") Func main () {f, err: = OS. Open ("D:\\test.txt") if err! = Nil {Panic ("Open failed!")} Defer f.close () Buff: = Make ([]byte, 1024x768) for n, err: = F.read (Buff); Err = = Nil; N, err = F.read (buff) {fmt. Print (String (Buff[:n]))}if err! = Nil {panic (FMT). Sprintf ("Read occurs error:%s", err)}}
The second method uses Ioutil.
File2.gopackage mainimport ("FMT" "Io/ioutil") func main () {buff, err: = Ioutil. ReadFile ("D:\\test.txt") if err! = Nil {Panic ("Open File failed!")} Fmt. Print (String (buff))}
Ioutil is simple enough to read all the contents of a file at once. If the file is large, it consumes a lot of memory and needs to be careful.
The third method, using Bufio,bufio is an interesting package, interested in reading the Bufio source code: Http://golang.org/src/pkg/bufio/bufio.go
File3.gopackage mainimport ("Bufio" "FMT" "IO" "OS") Func main () {f, err: = OS. Open ("D:\\test.txt") if err! = Nil {Panic ("Open failed!")} Defer f.close () b: = Bufio. Newreader (f) line, err: = b.readstring (' \ n ') for; Err = = Nil; Line, err = b.readstring (' \ n ') {FMT. Print (line)}if err = = Io. EOF {fmt. Print (line)} else {panic ("read occur error!")}}
Bufio provides a number of operations, such as Readstring,readbytes,readslice,readline, which require careful use of readslice and ReadLine:
1, Readslice very readline returned []byte is not a copy of copy, so the next time Readslice, this value is changed
2, ReadLine In addition to the above problem, the data returned by ReadLine does not include carriage return \ n and newline characters \ r
Specific can refer to Bufio's comments, written very clearly.
In fact, readsting and readbytes have been very useful, the parameters of both methods are delimiters, and when the delimiter is read, the function returns.