Click here to Skip to main content
15,900,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the below code that copies a text file from a directory to another with overwriting the file if exists 


What I'm looking for is to copy the file to the destination directory without overwriting, but keep both files. As in Windows for example, a copy of a file named "test" many times would be

test
test - Copy
test - Copy (2)
test - Copy (3)
text
text- Copy
text- Copy (2)
text- Copy (3) 


Any help would be appreciated ?


What I have tried:

package main

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

func main() {

	src := "./word1.txt"
	dest := "./words2.txt"

	bytesRead, err := ioutil.ReadFile(src)

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

	err = ioutil.WriteFile(dest, bytesRead, 0644)
	fmt.Println("Copied file \n")

	if err != nil {
		log.Fatal(err)
	}
}
Posted
Updated 6-Oct-21 21:29pm
v2

1 solution

Windows itself does this checking for you when you copy'n'paste or drag'n'drop files then if it finds a duplicate if uses a new file name, but your code is expected to know what it is doing, and no such checks are made.

If you want to do that, you will have to manually check for the existence of a file with that name, and if found create a new name, check for the existence of that, and repeat until you get a new, unused name to save under.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900