How to swap content of two files in Golang 1.20
In this video we are going to generate source code for the GoLang Program, How to swap content of two files using chatGPT.
After generating we will verify and run the generated code.
IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.
##############SOURCE CODE#########################
package main
import (
"io/ioutil"
"log"
"os"
)
func main() {
// Open the first file for reading and read its content.
file1, err := os.Open("file1.txt")
if err != nil {
log.Fatal(err)
}
defer file1.Close()
content1, err := ioutil.ReadAll(file1)
if err != nil {
log.Fatal(err)
}
// Open the second file for reading and read its content.
file2, err := os.Open("file2.txt")
if err != nil {
log.Fatal(err)
}
defer file2.Close()
content2, err := ioutil.ReadAll(file2)
if err != nil {
log.Fatal(err)
}
// Open the first file for writing and write the content of the second file to it.
file1, err = os.OpenFile("file1.txt", os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
log.Fatal(err)
}
defer file1.Close()
if _, err := file1.Write(content2); err != nil {
log.Fatal(err)
}
// Open the second file for writing and write the content of the first file to it.
file2, err = os.OpenFile("file2.txt", os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
log.Fatal(err)
}
defer file2.Close()
if _, err := file2.Write(content1); err != nil {
log.Fatal(err)
}
// Print a success message.
log.Println("Swapped content of file1.txt and file2.txt successfully.")
}
##############END OF SOURCE CODE#########################
Below is the explanation for the program:
In this program, we first open the first file (file1.txt) for reading using os.Open, read its content using ioutil.ReadAll, and close the file with defer file1.Close(). We repeat this process for the second file (file2.txt).
Next, we open the first file for writing using os.OpenFile with the os.O_WRONLY flag to indicate that we want to write to the file, and the os.O_TRUNC flag to truncate the file to zero length before writing to it. We then write the content of the second file to it using file1.Write(content2).
We repeat this process for the second file, opening it for writing and writing the content of the first file to it.
Finally, we print a success message.
Note that this program assumes that both files are not too large to fit into memory. If they are, a different approach will be necessary, such as reading and writing the files line by line.
#go #goprogramming #golang #golangtutorial #golanguage