以下是一个简单的golang实现linux下cp命令的示例代码:

package main

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

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

    source := os.Args[1]
    dest := os.Args[2]

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

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

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

    fmt.Printf("File copied: %s -> %s\n", source, dest)
}

该程序接受两个参数作为源文件和目标文件的路径,然后打开源文件并创建目标文件,最后使用io.Copy函数将源文件的内容复制到目标文件。如果出现任何错误,则程序将打印错误消息并退出。如果一切顺利,则程序将打印“文件已复制”的消息。

golang实现linux下cp命令

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

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