How to Copy File in Go: Simple and Effective Method
To copy a file in Go, open the source file with
os.Open, create the destination file with os.Create, and then use io.Copy to copy the contents. Finally, close both files to complete the operation.Syntax
Here is the basic syntax to copy a file in Go:
os.Open: Opens the source file for reading.os.Create: Creates or truncates the destination file for writing.io.Copy: Copies data from the source file to the destination file.Close: Closes both files to release resources.
go
srcFile, err := os.Open("source.txt") if err != nil { // handle error } dstFile, err := os.Create("destination.txt") if err != nil { // handle error } _, err = io.Copy(dstFile, srcFile) if err != nil { // handle error } srcFile.Close() dstFile.Close()
Example
This example shows how to copy a file named source.txt to destination.txt. It handles errors and closes files properly.
go
package main import ( "fmt" "io" "os" ) func main() { srcFile, err := os.Open("source.txt") if err != nil { fmt.Println("Error opening source file:", err) return } defer srcFile.Close() dstFile, err := os.Create("destination.txt") if err != nil { fmt.Println("Error creating destination file:", err) return } defer dstFile.Close() bytesCopied, err := io.Copy(dstFile, srcFile) if err != nil { fmt.Println("Error copying file:", err) return } fmt.Printf("Copied %d bytes from source.txt to destination.txt\n", bytesCopied) }
Output
Copied 1234 bytes from source.txt to destination.txt
Common Pitfalls
Common mistakes when copying files in Go include:
- Not closing files, which can cause resource leaks.
- Ignoring errors from
os.Open,os.Create, orio.Copy. - Copying files without handling permissions or metadata (this example copies only content).
Always check errors and use defer to close files safely.
go
package main import ( "io" "os" ) func main() { // Wrong: Not checking errors and not closing files srcFile, _ := os.Open("source.txt") dstFile, _ := os.Create("destination.txt") io.Copy(dstFile, srcFile) // Files not closed - bad practice // Right: Check errors and defer closing srcFile2, err := os.Open("source.txt") if err != nil { panic(err) } defer srcFile2.Close() dstFile2, err := os.Create("destination.txt") if err != nil { panic(err) } defer dstFile2.Close() _, err = io.Copy(dstFile2, srcFile2) if err != nil { panic(err) } }
Key Takeaways
Use os.Open and os.Create to open source and destination files respectively.
Use io.Copy to transfer file contents efficiently.
Always check for errors and close files with defer to avoid resource leaks.
This method copies only file content, not permissions or metadata.
Handle errors properly to make your file copy robust.