This is a creation in Article, where the information may have evolved or changed.
Today, when studying the copy of Go, it is found that the copied files are always larger than the source files, the program is as follows
Package Mainimport ( "OS" " log" " io" " FMT") func main () { file, err: = OS. Open ("C:/users/desktop/123123.txt")//for Read access. Defer file. Close () if err! = Nil { log. Fatal (Err. Error ()) } chunks: = make ([]byte,1024) Buff: = Make ([]byte, 1024x768) for{ count, err: = file. Read (Buff) if err! = Nil && Err! = Io. Eof{panic (ERR)} if 0==count {break} chunks = append (Chunks,buff[:count] ...) } File1,err: = os. Create ("C:/users/desktop/123123123.txt") defer file1. Close () file1. Write (Chunks)}
If you write a program like this, it causes the copied file to be 1024 bytes larger than the source file.
In fact, the main reason for the built-in function of the go language is append
I experimented, the append function when the two slices together, not to put the second slice into the first slice, if it is directly put in, the length of the slice will not change, as follows
A:=make ([]byte,10) B:=make ([]byte,2) fmt. Println (Len (Append (A, b ...))
Should output 10, and actually output 12!
So, in the example of copying files,
Chunks: = make ([]byte,1024) should be changed to chunks: = make ([]byte,0)
In this way, the copied files are correct!
Continue to add a little bit of append usage
The first is that the first parameter is a slice, which can be used to pass many (not fixed) elements, such as:
Append ([]byte,1,2,3)
The second use, is to pass two slices, so that only two parameters can be passed, and the second parameter to ... End, as in the example above
A:=make ([]byte,10) B:=make ([]byte,2) fmt. Println (Len (Append (A, b ...))
Finally, a little bit more, when you read a file, something you don't understand.
If err! = Nil && Err! = Io. Eof{panic (ERR)}
This sentence involves two knowledge, one is the exception in the Go language, and the other is EOF
Go language of the anomaly mechanism, there is a blog written very well, read the blog
EOF indicates file end exception (read out)