github.com/qjfoidnh/BaiduPCS-Go@v0.0.0-20231011165705-caa18a3765f3/internal/pcsupdate/updatefile.go (about)

     1  package pcsupdate
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"os"
     7  	"path/filepath"
     8  )
     9  
    10  func update(targetPath string, src io.Reader) error {
    11  	info, err := os.Stat(targetPath)
    12  	if err != nil {
    13  		fmt.Printf("Warning: %s\n", err)
    14  		return nil
    15  	}
    16  
    17  	privMode := info.Mode()
    18  
    19  	oldPath := filepath.Join(filepath.Dir(targetPath), "old"+filepath.Base(targetPath))
    20  
    21  	err = os.Rename(targetPath, oldPath)
    22  	if err != nil {
    23  		return err
    24  	}
    25  
    26  	newFile, err := os.OpenFile(targetPath, os.O_CREATE|os.O_WRONLY, privMode)
    27  	if err != nil {
    28  		return err
    29  	}
    30  
    31  	_, err = io.Copy(newFile, src)
    32  	if err != nil {
    33  		return err
    34  	}
    35  
    36  	err = newFile.Close()
    37  	if err != nil {
    38  		fmt.Printf("Warning: 关闭文件发生错误: %s\n", err)
    39  	}
    40  
    41  	err = os.Remove(oldPath)
    42  	if err != nil {
    43  		fmt.Printf("Warning: 移除旧文件发生错误: %s\n", err)
    44  	}
    45  	return nil
    46  }