dongnuochen9449 2019-01-24 13:58
浏览 174
已采纳

如何正确复制二进制文件

I use the following code which build binary programmatically the binary is build successfully but now I want to copy it via code to go/bin path, and I was able to do it, but it copy the file but not as executable.

what could be wrong ? the source file is executable

bPath := filepath.FromSlash("./integration/testdata/" + fileName)
cmd := exec.Command("go", "build", "-o", bPath, ".")
cmd.Dir = filepath.FromSlash("../")
err := cmd.Run()
if err != nil {
    fmt.Println("binary creation failed: ", err)
}

fmt.Println(os.Getenv("GOPATH"))
dir, _ := os.Getwd()
srcPath := filepath.Join(dir, "testdata", , fileName)
targetPath := filepath.Join(os.Getenv("GOPATH"),"/bin/",fileName)
copy(srcPath, targetPath)

The copy is:

func copy(src string, dst string) error {
    // Read all content of src to data
    data, err := ioutil.ReadFile(src)
    if err != nil {
        return err
    }
    // Write data to dst
    err = ioutil.WriteFile(dst, data, 0644)
    if err != nil {
        return err
    }

    return nil
}
  • 写回答

1条回答 默认 最新

  • dongmo20030416 2019-01-24 14:02
    关注

    The problem is with the permission bitmask you provide: 0644. It does not include executable permission, which is the lowest bit in each group.

    So instead use 0755, and the result file will be executable by everyone:

    err = ioutil.WriteFile(dst, data, 0755)
    

    Check out Wikipedia Chmod for the meaning of the bitmask.

    The relevant bitmask table:

    #    Permission               rwx    Binary
    -------------------------------------------
    7    read, write and execute  rwx    111
    6    read and write           rw-    110
    5    read and execute         r-x    101
    4    read only                r--    100
    3    write and execute        -wx    011
    2    write only               -w-    010
    1    execute only             --x    001
    0    none                     ---    000
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?