In Go the os.Rename
func
moves a file from one location to another. But if we want to copy the file, we cannot just move it.
With ioutil
, we can read in the contents of a file (with ReadAll
). Then we can write the copy to a new location. This logic can be placed in a reusable func
.
Here we have a main func
that begins with 2 local variables. We must specify a valid input path (the source) and output path (the target).
os.Open
func
. We just ignore errors, but these could be checked.ioutil.ReadAll
. Again we just ignore errors.ioutil.WriteFile
to write the data to a new location—the target location for the copy.package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
inputPath := `C:\programs\file.txt`
outputPath := `C:\programs\copy.txt`
// Part 1: open input file.
inputFile, _ := os.Open(inputPath)
// Part 2: call ReadAll to get contents of input file.
data, _ := ioutil.ReadAll(inputFile)
// Part 3: write data to copy file.
ioutil.WriteFile(outputPath, data, 0)
fmt.Println("DONE")
}DONE
When we want to copy a file, we cannot just call os.Rename
as the original is deleted. Instead, we can use helpful methods from ioutil
.
file.txt: 60 bytes copy.txt: 60 bytes
Often it is important to copy files for deployment of projects (like websites or applications). With the code here, we can copy files without deleting the originals.