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

将可执行的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条回答 默认 最新

  • duanli6834 2018-07-17 12:23
    关注

    I have found an error.

    The process cannot access the file because it is being used by another process.

    I was trying to copy the .exe file to its own path.

    func copy(src, dst string) error {
        if _, err := os.Stat(dst); os.IsNotExist(err) {
            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 nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?