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.
Copy example. 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).
Part 1 We open an input file with the os.Open func. We just ignore errors, but these could be checked.
Part 2 We read in the data from the file with ioutil.ReadAll. Again we just ignore errors.
Part 3 We call 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
Notes, copying. 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
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.