How to copy data from one file to another in Go with the io package?

To copy data from one file to another in Go using the io package, you can follow these steps:

  1. Import the necessary packages:
import ( "os" "io" )
  1. Open the source file for reading:
sourceFile, err := os.Open("path/to/source/file.txt") if err != nil { panic(err) } defer sourceFile.Close()
  1. Create the destination file for writing:
destinationFile, err := os.Create("path/to/destination/file.txt") if err != nil { panic(err) } defer destinationFile.Close()
  1. Use the 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) }
  1. To ensure that all the data has been written to the destination file, you can call the 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.