Search code examples
gofile-copying

How do I copy a file without overwriting an existing file in Go?


How to create a new file with the given name if the file exists

eg : if word_destination.txt exists copy content to word_destination(1).txt

Any help would be appreciated...

package main

import (
    "fmt"
    "io/ioutil"
    "os"
)


func main() {

    src := ./word_source.txt
    desti := ./folder/word_destination.txt

    //if file exists want to copy it to the word_destination(1).txt
    if _, err := os.Stat(desti); err == nil {
        // path/to/whatever exists
        fmt.Println("File Exists")

    } else {
        fmt.Println("File does not Exists")
        bytesRead, err := ioutil.ReadFile(src)

        if err != nil {
            log.Fatal(err)
        }

Solution

  • func tryCopy(src, dst string) error {
        in, err := os.Open(src)
        if err != nil {
            return err
        }
        defer in.Close()
    
        out, err := os.OpenFile(dst, os.O_CREATE| os.O_EXCL, 0644)
        if err != nil {
            return err
        }
        defer out.Close()
    
        _, err = io.Copy(out, in)
        if err != nil {
            return err
        }
        return out.Close()
    }
    // ......
    if _, err := os.Stat(desti); err == nil {
        // path/to/whatever exists
        fmt.Println("File Exists")
        for i := 1; ; i++ {
            ext := filepath.Ext(desti)
            newpath := fmt.Sprintf("%s(%d)%s", strings.TrimSuffix(desti, ext), i, ext)
    
            err := tryCopy(desti, newpath)
            if err == nil {
                break;
            }
            
            if os.IsExists(err) {
                continue;
            } else {
                return err;
            }
        }
    }