How to compare two files and print the difference in Golang 1.20



How to compare two files and print the difference in Golang 1.20

How to compare two files and print the difference in Golang 1.20

In this video we are going to generate source code for the GoLang Program, How to compare two files and print the difference 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 (
“bufio”
“fmt”
“os”
)

func main() {
// Open the first file for reading.
file1, err := os.Open(“file1.txt”)
if err != nil {
fmt.Println(err)
return
}
defer file1.Close()

// Open the second file for reading.
file2, err := os.Open(“file2.txt”)
if err != nil {
fmt.Println(err)
return
}
defer file2.Close()

// Create a scanner for each file.
scanner1 := bufio.NewScanner(file1)
scanner2 := bufio.NewScanner(file2)

// Scan each file line by line and compare the lines.
lineNumber := 1
for scanner1.Scan() && scanner2.Scan() {
line1 := scanner1.Text()
line2 := scanner2.Text()
if line1 != line2 {
fmt.Printf(“Difference found at line %d:n”, lineNumber)
fmt.Printf(“- %sn+ %sn”, line1, line2)
}
lineNumber++
}

// If one file has more lines than the other, print the difference.
for scanner1.Scan() {
fmt.Printf(“Difference found at line %d:n”, lineNumber)
fmt.Printf(“- %sn”, scanner1.Text())
lineNumber++
}
for scanner2.Scan() {
fmt.Printf(“Difference found at line %d:n”, lineNumber)
fmt.Printf(“+ %sn”, scanner2.Text())
lineNumber++
}
}

Below is the explanation for the program:

In this program, we open two files, file1.txt and file2.txt, for reading using the os.Open function.
We create a scanner for each file using bufio.NewScanner.

We then scan each file line by line using scanner1.Scan() and scanner2.Scan().
For each pair of lines, we compare them using the != operator. If they are not equal,
we print the line number and the two lines with a – indicating the line from the first file and a + indicating the line from the second file.

Finally, if one file has more lines than the other,
we print the difference by scanning the remaining lines and printing them with either a – or a + depending on which file they came from.

Note that this program assumes that both files have the same number of lines. If they don’t, the output may be incorrect.

#go #goprogramming #golang #golangtutorial #golanguage