dtsc14683
2018-07-17 06:43
浏览 345
已采纳

将可执行的golang文件复制到另一个文件夹

I wonder if possible to copy running .exe file to another folder. I am trying to do this using usual copy approach in Go like that.

func copy(src, dst string) error {
    in, err := os.Open(src)
    if err != nil {
        return err
    }
    defer in.Close()

    out, err := os.Create(dst)
    if err != nil {
        return err
    }
    defer out.Close()

    _, err = io.Copy(out, in)
    if err != nil {
        return err
    }
    return out.Close()
}

...

copyErr := copy(os.Args[0], "D:"+"\\"+"whs.exe")
if copyErr != nil {
    log.Panicf("copy -> %v", copyErr)
}

The file copied with the same size but I can't open it correctly. I have only a fast cmd flash. After several milliseconds, cmd is closing and I can't see even any errors. I was trying to write errors to log file but it's empty.

f, err := os.OpenFile("debug.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777)
if err != nil {
    log.Panicf("setLogOutput -> %v", err)
}
defer f.Close()

log.SetOutput(f)

If I open not copied .exe file everything works correctly.

I've reduced my program to only one main method. The result was the same.

func main() {
    log.Println("Starting...")
    copyErr := copy(os.Args[0], "F:"+"\\"+"whs.exe")
    if copyErr != nil {
        log.Panicf("copy -> %v", copyErr)
    }
    os.Stdin.Read([]byte{0})
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题