To copy data from one file to another in Go using the io
package, you can follow these steps:
import (
"os"
"io"
)
sourceFile, err := os.Open("path/to/source/file.txt")
if err != nil {
panic(err)
}
defer sourceFile.Close()
destinationFile, err := os.Create("path/to/destination/file.txt")
if err != nil {
panic(err)
}
defer destinationFile.Close()
io.Copy()
function to copy the data from the source file to the destination file:_, err = io.Copy(destinationFile, sourceFile)
if err != nil {
panic(err)
}
Sync()
function on the destination file:err = destinationFile.Sync()
if err != nil {
panic(err)
}
Here's the complete example:
package main
import (
"os"
"io"
)
func main() {
// Open the source file for reading
sourceFile, err := os.Open("path/to/source/file.txt")
if err != nil {
panic(err)
}
defer sourceFile.Close()
// Create the destination file for writing
destinationFile, err := os.Create("path/to/destination/file.txt")
if err != nil {
panic(err)
}
defer destinationFile.Close()
// Copy the data from the source file to the destination file
_, err = io.Copy(destinationFile, sourceFile)
if err != nil {
panic(err)
}
// Ensure all data is written to the destination file
err = destinationFile.Sync()
if err != nil {
panic(err)
}
}
Make sure to replace "path/to/source/file.txt"
and "path/to/destination/file.txt"
with the actual paths to your source and destination files.