golang : copy the contents of a file to another file
package main
import (
"fmt"
"io"
"os"
)
func copyFileContents(src, dst string) (err error) {
in, err := os.Open(src)
if err != nil {
return
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return
}
defer func() {
cerr := out.Close()
if err == nil {
err = cer
}
}()
if _, err = io.Copy(out, in); err != nil {
return
}
err = out.Sync()
return
}
func main() {
err := copyFileContents("main.go", "test.test")
if err != nil {
panic(err)
}
fmt.Println("copy success!!!")
}
In the program, the file content of main.go is copied to test.test
After running the code, you can view the content of test.test
Summarize:
Note that the sync function
err = out.Sync()
After the copy is completed, you need to judge the status of the file.
// Sync commits the current contents of the file to stable storage.
// Typically, this means flushing the file system's in-memory copy
// of recently written data to disk.
func (f *File) Sync() error {
if err := f.checkValid("sync"); err != nil {
return er
}
if e := f.pfd.Fsync(); e != nil {
return f.wrapErr("sync", e)
}
return nil
Fsync() will be called in the sync function to place the data on the disk
func (fd *FD) Fsync() error {
if err := fd.incref(); err != nil {
return er
}
defer fd.decref()
_, e1 := fcntl(fd.Sysfd, syscall.F_FULLFSYNC, 0)
return e1
}