package main
import (
"fmt"
"io"
"io/ioutil"
"os"
)
func main() {
file, err := os.Open("HelloWorld")
if nil != err {
fmt.Println(err)
}
defer file.Close()
fileTo, err := os.Create("fileTo")
if nil != err {
fmt.Println(err)
}
defer file.Close()
_, err = io.Copy(fileTo, file)
if nil != err {
fmt.Println(err)
}
fileByteOne, err := ioutil.ReadAll(file)
if nil != err {
fmt.Println(err)
}
fmt.Println(fileByteOne)
}
io.Copy() will erase the file content, the output is :
[]
Copy(dst Writer, src Reader) copies from src to dst, it will erase the src content. Is there any way to avoid erasing?
io.Copy(fileTo, file)
will erase the file content
It won't. But it will move the read position to EOF
, meaning the next ioutil.ReadAll()
will start at ... EOF
.
You could close it and re-open 'file
'before your ioutil.ReadAll()
.
By the way, you have two defer file.Close()
instances: the second one should be defer fileTo.Close()
.
Or, simpler, reset it with a SectionReader.Seek()
, as suggested by PeterSO's answer.
_, err = file.Seek(0, os.SEEK_SET)
It is also illustrated in GoByExamples Reading Files:
There is no built-in rewind, but
Seek(0, 0)
accomplishes this.
(os.SEEK_SET
is define in os constants, as 0
)
const SEEK_SET int = 0 // seek relative to the origin of the file
Reset from the end of the file to the start of the file with a seek. For example.
package main
import (
"fmt"
"io"
"io/ioutil"
"os"
)
func main() {
file, err := os.Open("HelloWorld")
if err != nil {
fmt.Println(err)
}
defer file.Close()
fileTo, err := os.Create("fileTo")
if err != nil {
fmt.Println(err)
}
defer fileTo.Close()
_, err = io.Copy(fileTo, file)
if err != nil {
fmt.Println(err)
}
_, err = file.Seek(0, os.SEEK_SET) // start of file
if err != nil {
fmt.Println(err)
}
fileByteOne, err := ioutil.ReadAll(file)
if err != nil {
fmt.Println(err)
}
fmt.Println(fileByteOne)
}
Output:
[72 101 108 108 111 44 32 87 111 114 108 100 33 10]