以下是使用 Golang 实现 Linux 下 cp 命令,复制文件权限及文件扩展属性的示例代码:

package main

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

func main() {
    if len(os.Args) != 3 {
        fmt.Println("Usage: cp src_file dst_file")
        os.Exit(1)
    }

    srcFile, err := os.Open(os.Args[1])
    if err != nil {
        fmt.Printf("Error opening source file: %v\n", err)
        os.Exit(1)
    }
    defer srcFile.Close()

    dstFile, err := os.Create(os.Args[2])
    if err != nil {
        fmt.Printf("Error creating destination file: %v\n", err)
        os.Exit(1)
    }
    defer dstFile.Close()

    _, err = io.Copy(dstFile, srcFile)
    if err != nil {
        fmt.Printf("Error copying file: %v\n", err)
        os.Exit(1)
    }

    srcStat, err := os.Stat(os.Args[1])
    if err != nil {
        fmt.Printf("Error getting source file info: %v\n", err)
        os.Exit(1)
    }

    err = os.Chmod(os.Args[2], srcStat.Mode())
    if err != nil {
        fmt.Printf("Error setting file permissions: %v\n", err)
        os.Exit(1)
    }

    if srcStat.Mode().IsRegular() {
        srcFd, err := syscall.Open(os.Args[1], syscall.O_RDONLY, 0)
        if err != nil {
            fmt.Printf("Error opening source file: %v\n", err)
            os.Exit(1)
        }
        defer syscall.Close(srcFd)

        dstFd, err := syscall.Open(os.Args[2], syscall.O_WRONLY, 0)
        if err != nil {
            fmt.Printf("Error opening destination file: %v\n", err)
            os.Exit(1)
        }
        defer syscall.Close(dstFd)

        var attr *syscall.GetxattrListReply
        attr, err = syscall.GetxattrList(os.Args[1])
        if err != nil {
            fmt.Printf("Error getting extended attributes: %v\n", err)
            os.Exit(1)
        }

        for _, name := range attr.Attrs {
            var value []byte
            value, err = syscall.Getxattr(os.Args[1], name)
            if err != nil {
                fmt.Printf("Error getting extended attribute ' %s ': %v\n", name, err)
                os.Exit(1)
            }

            err = syscall.Setxattr(os.Args[2], name, value, 0)
            if err != nil {
                fmt.Printf("Error setting extended attribute ' %s ': %v\n", name, err)
                os.Exit(1)
            }
        }
    }
}

使用示例:

$ go run cp.go src_file dst_file
Golang 实现 Linux 下 cp 命令:复制文件权限和扩展属性

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

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