Go, also known as Golang, is a statically typed, compiled programming language designed by Google. It is known for its simplicity and efficient management of dependencies. Copying or moving files in Go can be achieved using the built-in "os" and "io" packages.
Copying a File
To copy a file in Go, you need to open both the source and destination files and use a buffer to read and write the data. Here is a step-by-step guide on how to accomplish this.
package main
import (
"io"
"os"
"log"
)
func CopyFile(src, dst string) error {
sourceFile, err := os.Open(src)
if err != nil {
return err
}
defer sourceFile.Close()
destinationFile, err := os.Create(dst)
if err != nil {
return err
}
defer destinationFile.Close()
_, err = io.Copy(destinationFile, sourceFile)
if err != nil {
return err
}
return nil
}
func main() {
src := "source.txt"
dst := "destination.txt"
err := CopyFile(src, dst)
if err != nil {
log.Fatalf("File copy failed: %v", err)
}
log.Println("File copied successfully!")
}
In this example, we use os.Open to open the source file and os.Create to create the destination file. The io.Copy function is then used to buffer the data from the source to the destination file. Don't forget to handle errors and defer the closure of files to clean up resources.
Moving a File
To move a file, you can use the os.Rename function, which effectively changes the file's path.
package main
import (
"os"
"log"
)
func MoveFile(src, dst string) error {
err := os.Rename(src, dst)
if err != nil {
return err
}
return nil
}
func main() {
src := "source.txt"
dst := "new_location/destination.txt"
err := MoveFile(src, dst)
if err != nil {
log.Fatalf("File move failed: %v", err)
}
log.Println("File moved successfully!")
}
Here, os.Rename moves the file from the source path to the destination path. This function works well for renaming files or moving them across directories within the same file system. However, be cautious when moving between different physical drives as it might fail in such cases.
By using both CopyFile and MoveFile functions, you can manage files efficiently in Go.