在 Linux 下使用 Golang 复制文件,可以使用 os 包中的函数来实现。具体步骤如下:

  1. 打开源文件和目标文件,使用 os.Openos.Create 函数来打开文件,获取源文件和目标文件的句柄。

  2. 使用 io.Copy 函数将源文件的内容复制到目标文件中。

  3. 使用 os.Chmod 函数将目标文件的权限设置为与源文件相同。

  4. 使用 syscall.Setxattr 函数将源文件的扩展属性复制到目标文件中。

示例代码如下:

package main

import (
    "fmt"
    "io"
    "os"
    "syscall"
)

func main() {
    srcFile := 'source.txt'
    destFile := 'destination.txt'

    src, err := os.Open(srcFile)
    if err != nil {
        fmt.Println("Error opening source file:", err)
        return
    }
    defer src.Close()

    dest, err := os.Create(destFile)
    if err != nil {
        fmt.Println("Error creating destination file:", err)
        return
    }
    defer dest.Close()

    _, err = io.Copy(dest, src)
    if err != nil {
        fmt.Println("Error copying file contents:", err)
        return
    }

    info, err := os.Stat(srcFile)
    if err != nil {
        fmt.Println("Error getting source file info:", err)
        return
    }

    err = os.Chmod(destFile, info.Mode())
    if err != nil {
        fmt.Println("Error setting destination file permissions:", err)
        return
    }

    xattrs, err := syscall.Listxattr(srcFile)
    if err != nil {
        fmt.Println("Error getting source file xattrs:", err)
        return
    }

    for _, xattr := range xattrs {
        value := make([]byte, 1024)
        size, err := syscall.Getxattr(srcFile, xattr, value)
        if err != nil {
            fmt.Println("Error getting source file xattr value:", err)
            continue
        }
        err = syscall.Setxattr(destFile, xattr, value[:size], 0)
        if err != nil {
            fmt.Println("Error setting destination file xattr:", err)
            continue
        }
    }

    fmt.Println("File copied successfully!")
}

注意:复制文件时需要保证目标文件所在的目录已经存在。

Golang 复制文件:Linux 环境下保留权限和扩展属性

原文地址: http://www.cveoy.top/t/topic/mtME 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录