[go] Go 언어의 경로를 이용한 파일 및 디렉토리 이진 병합
Go 언어를 사용하여 파일 및 디렉토리를 병합하고 싶다면, path/filepath
패키지를 사용하여 간단하게 이를 수행할 수 있습니다. 이 패키지는 파일 경로를 다루는 데 필요한 함수들을 제공합니다. 이제 이해를 돕기 위해 몇 가지 예시를 살펴보겠습니다.
파일 병합
만약 두 개의 파일을 이진 병합하고 싶다면, 다음과 같이 코드를 작성할 수 있습니다:
package main
import (
"io"
"os"
)
func main() {
input1, _ := os.Open("file1.txt")
defer input1.Close()
input2, _ := os.Open("file2.txt")
defer input2.Close()
output, _ := os.Create("output.txt")
defer output.Close()
io.Copy(output, input1)
io.Copy(output, input2)
}
위의 예시에서, io.Copy
함수를 사용하여 두 개의 파일을 output.txt
로 이진 병합하고 있습니다.
디렉토리 병합
디렉토리를 이진 병합하기 위해서는 filepath.Walk
함수를 사용할 수 있습니다. 예를 들어:
package main
import (
"io"
"os"
"path/filepath"
)
func main() {
destDir := "./destination"
sourceDir := "./source"
filepath.Walk(sourceDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
sourceFile, err := os.Open(path)
defer sourceFile.Close()
if err != nil {
return err
}
destPath := filepath.Join(destDir, path[len(sourceDir):])
destFile, err := os.Create(destPath)
defer destFile.Close()
if err != nil {
return err
}
io.Copy(destFile, sourceFile)
}
return nil
})
}
위 코드에서 filepath.Walk
함수는 소스 디렉토리의 모든 파일을 순회하며, 각 파일을 대상 디렉토리로 복사하고 있습니다.
이처럼 Go 언어의 path/filepath
패키지를 사용하여 파일 및 디렉토리를 이진 병합하는 방법을 알아보았습니다. 필요에 따라 적절히 활용하여 효과적으로 파일 및 디렉토리를 병합할 수 있습니다.
참고 자료
- Go 언어 공식 문서: https://golang.org/pkg/path/filepath/
- “The Go Programming Language” (Alan A. A. Donovan, Brian W. Kernighan) - 2015, Addison-Wesley Professional