go :複製文件內容到另一個文件

背景:
本文實驗,從一個文件拷貝文件內容到另外一個文件
代碼

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 = cerr
		}
	}()
	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!!!")
}

程序中,將 main.go 的文件內容拷貝到了 test.test 裏面
運行代碼之後可以查看 test.test內容

總結:
需要注意的是 sync函數
err = out.Sync()
複製完成之後需要判斷一下文件狀態,

// 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 err
	}
	if e := f.pfd.Fsync(); e != nil {
		return f.wrapErr("sync", e)
	}
	return nil
}

sync函數中會調用Fsync()將數據落盤

func (fd *FD) Fsync() error {
	if err := fd.incref(); err != nil {
		return err
	}
	defer fd.decref()

	_, e1 := fcntl(fd.Sysfd, syscall.F_FULLFSYNC, 0)
	return e1
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章