Introduction
Copying a file involves creating a new file with the same contents as an existing one. In Go, this can be achieved by reading the contents of the source file and writing them to the destination file. This guide will demonstrate how to write a Go program that copies a file.
Problem Statement
Create a Go program that:
- Takes the source filename and destination filename as input.
- Copies the contents of the source file to the destination file.
- Displays a message indicating whether the file was successfully copied or if an error occurred.
Example:
- Input: Source filename
"source.txt", Destination filename"destination.txt" - Output:
File copied successfully.or
Error copying file: file does not exist.
Solution Steps
- Import the Necessary Packages: Use
import "fmt",import "io", andimport "os"for file operations and I/O operations. - Write a Function to Copy the File: Implement a function that reads the source file and writes its contents to the destination file.
- Write the Main Function: Define the
mainfunction, which is the entry point of every Go program. - Prompt the User to Enter the Source and Destination Filenames: Use
fmt.Scanlnorfmt.Scanfto take the filenames as input. - Call the Function to Copy the File: Use the function to copy the file.
- Display the Result: Use
fmt.Printlnto display whether the file was successfully copied or if an error occurred.
Go Program
package main
import (
"fmt"
"io"
"os"
)
// Step 2: Implement a function to copy the file
func copyFile(src, dst string) error {
// Open the source file
sourceFile, err := os.Open(src)
if err != nil {
return err
}
defer sourceFile.Close()
// Create the destination file
destinationFile, err := os.Create(dst)
if err != nil {
return err
}
defer destinationFile.Close()
// Copy the contents from the source file to the destination file
_, err = io.Copy(destinationFile, sourceFile)
if err != nil {
return err
}
// Flush the file's write buffer to ensure all data is written
err = destinationFile.Sync()
if err != nil {
return err
}
return nil
}
/**
* Go Program to Copy a File
* Author: https://www.javaguides.net/
*/
func main() {
// Step 4: Prompt the user to enter the source and destination filenames
var src, dst string
fmt.Print("Enter the source filename: ")
fmt.Scanln(&src)
fmt.Print("Enter the destination filename: ")
fmt.Scanln(&dst)
// Step 5: Call the function to copy the file
err := copyFile(src, dst)
if err != nil {
fmt.Println("Error copying file:", err)
} else {
fmt.Println("File copied successfully.")
}
}
Explanation
Step 2: Implement a Function to Copy the File
- The
copyFilefunction handles the process of copying the file:- It opens the source file using
os.Open. If the source file does not exist or cannot be opened, it returns an error. - It creates the destination file using
os.Create. If the destination file cannot be created, it returns an error. - It copies the contents of the source file to the destination file using
io.Copy. - Finally, it flushes the write buffer to ensure that all data is written to the destination file using
destinationFile.Sync().
- It opens the source file using
Step 3: Write the Main Function
- The
mainfunction prompts the user for the source and destination filenames and callscopyFileto copy the file.
Step 4: Prompt the User to Enter the Source and Destination Filenames
- The program prompts the user to enter the source and destination filenames using
fmt.Printand reads the input usingfmt.Scanln.
Step 5: Call the Function to Copy the File
- The program calls
copyFilewith the provided filenames to copy the file.
Step 6: Display the Result
- The program prints a message indicating whether the file was successfully copied or if an error occurred using
fmt.Println.
Output Example
Example 1:
Enter the source filename: source.txt
Enter the destination filename: destination.txt
File copied successfully.
Example 2:
Enter the source filename: nonexistentfile.txt
Enter the destination filename: newfile.txt
Error copying file: open nonexistentfile.txt: no such file or directory
Example 3 (Empty input):
Enter the source filename:
Enter the destination filename:
Error copying file: open : no such file or directory
Conclusion
This Go program demonstrates how to copy a file using the os and io packages. It covers basic file operations such as opening, creating, reading, writing, and handling errors in Go. This example is useful for beginners learning Go programming and understanding how to perform file manipulation tasks effectively.