[go] 파일 경로에서 파일 내용 비교하기

이 문서에서는 Go 언어를 사용하여 두 개의 파일 경로에서 파일 내용을 비교하는 방법에 대해 알아보겠습니다. 이를 통해 파일의 내용이 동일한지 여부를 확인할 수 있습니다.

파일 읽기

우선, 파일의 내용을 읽어오는 방법에 대해 살펴보겠습니다. Go 언어에서는 ioutil 패키지를 사용하여 파일을 읽고 쓸 수 있습니다.

package main

import (
    "io/ioutil"
    "fmt"
)

func readFile(filePath string) (string, error) {
    content, err := ioutil.ReadFile(filePath)
    if err != nil {
        return "", err
    }
    return string(content), nil
}

func main() {
    file1Content, err := readFile("file1.txt")
    if err != nil {
        fmt.Println("Error reading file1:", err)
        return
    }

    file2Content, err := readFile("file2.txt")
    if err != nil {
        fmt.Println("Error reading file2:", err)
        return
    }

    // 파일 내용 비교
    if file1Content == file2Content {
        fmt.Println("File contents are the same")
    } else {
        fmt.Println("File contents are different")
    }
}

위의 예제에서 readFile 함수를 사용하여 파일의 내용을 읽어오고, 메인 함수에서 해당 함수를 호출하여 파일 내용을 읽어와 비교하고 있습니다.

실행 방법

위의 예제 코드를 compareFiles.go 파일에 작성하고 다음 명령을 사용하여 실행할 수 있습니다.

go run compareFiles.go

위의 코드를 실행하면 두 파일의 내용을 비교하여 결과를 출력할 것입니다.

이제 Go 언어를 활용해 파일 경로에서 파일 내용을 비교하는 방법에 대해 알아보았습니다.