fileutil

package
v0.0.0-...-14a125a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2025 License: MIT Imports: 19 Imported by: 0

README

fileutil - Extreme Simplicity File and Path Utilities / 극도로 간단한 파일 및 경로 유틸리티

Go Version License Version

Overview / 개요

The fileutil package provides extreme simplicity file and path utilities for Golang, reducing 20+ lines of repetitive file manipulation code to just 1-2 lines.

fileutil 패키지는 Golang을 위한 극도로 간단한 파일 및 경로 유틸리티를 제공하며, 20줄 이상의 반복적인 파일 조작 코드를 단 1-2줄로 줄입니다.

Key Features / 주요 기능
  • Safe file operations with automatic directory creation / 자동 디렉토리 생성을 사용한 안전한 파일 작업
  • Cross-platform compatibility / 크로스 플랫폼 호환성
  • Comprehensive file/directory operations / 포괄적인 파일/디렉토리 작업
  • Path manipulation and validation / 경로 조작 및 검증
  • File hashing and checksums / 파일 해싱 및 체크섬
  • Progress callbacks for long operations / 긴 작업을 위한 진행 상황 콜백
  • Atomic file operations / 원자적 파일 작업
  • Zero external dependencies / 외부 의존성 없음 (yaml 제외)
Design Philosophy / 설계 철학

"20줄 → 1줄" (20 lines → 1 line)

Before / 이전:

// 20+ lines of code
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0755); err != nil {
    return err
}
file, err := os.Create(path)
if err != nil {
    return err
}
defer file.Close()
if _, err := file.WriteString(content); err != nil {
    return err
}
// More boilerplate...

After / 이후:

// 1 line of code
err := fileutil.WriteString("path/to/file.txt", "Hello, World!")

Installation / 설치

go get github.com/arkd0ng/go-utils/fileutil

Quick Start / 빠른 시작

Basic File Operations / 기본 파일 작업
package main

import (
    "fmt"
    "log"

    "github.com/arkd0ng/go-utils/fileutil"
)

func main() {
    // Write file with automatic directory creation / 자동 디렉토리 생성과 함께 파일 쓰기
    err := fileutil.WriteString("path/to/file.txt", "Hello, World!")
    if err != nil {
        log.Fatal(err)
    }

    // Read file / 파일 읽기
    content, err := fileutil.ReadString("path/to/file.txt")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(content) // Output: Hello, World!

    // Copy file / 파일 복사
    err = fileutil.CopyFile("source.txt", "destination.txt")
    if err != nil {
        log.Fatal(err)
    }
}
Path Operations / 경로 작업
// Join paths / 경로 결합
path := fileutil.Join("home", "user", "documents", "file.txt")
// Output: home/user/documents/file.txt

// Get base name / 기본 이름 가져오기
base := fileutil.Base(path)
// Output: file.txt

// Get extension / 확장자 가져오기
ext := fileutil.Ext(path)
// Output: .txt

// Change extension / 확장자 변경
newPath := fileutil.ChangeExt(path, ".md")
// Output: home/user/documents/file.md
File Information / 파일 정보
// Check if file exists / 파일 존재 확인
exists := fileutil.Exists("path/to/file.txt")

// Check if it's a file / 파일인지 확인
isFile := fileutil.IsFile("path/to/file.txt")

// Get file size / 파일 크기 가져오기
size, err := fileutil.Size("path/to/file.txt")

// Get human-readable size / 사람이 읽기 쉬운 크기 가져오기
sizeStr, err := fileutil.SizeHuman("path/to/file.txt")
// Output: "1.5 KB" or "2.3 MB"
Directory Operations / 디렉토리 작업
// Create directory / 디렉토리 생성
err := fileutil.MkdirAll("path/to/directory")

// List files / 파일 나열
files, err := fileutil.ListFiles("path/to/directory")

// Find .txt files recursively / .txt 파일 재귀적으로 찾기
txtFiles, err := fileutil.FindFiles(".", func(path string, info os.FileInfo) bool {
    return fileutil.Ext(path) == ".txt"
})

// Calculate directory size / 디렉토리 크기 계산
size, err := fileutil.DirSize("path/to/directory")
File Hashing / 파일 해싱
// Calculate MD5 hash / MD5 해시 계산
md5Hash, err := fileutil.MD5("path/to/file.txt")

// Calculate SHA256 hash / SHA256 해시 계산
sha256Hash, err := fileutil.SHA256("path/to/file.txt")

// Compare two files by hash / 두 파일을 해시로 비교
same, err := fileutil.CompareHash("file1.txt", "file2.txt")

// Verify checksum / 체크섬 검증
valid, err := fileutil.VerifyChecksum("file.txt", "expected-checksum")
Copy with Progress / 진행 상황과 함께 복사
// Copy with progress callback / 진행 상황 콜백과 함께 복사
err := fileutil.CopyFile("large-file.dat", "backup.dat",
    fileutil.WithProgress(func(written, total int64) {
        percent := float64(written) / float64(total) * 100
        fmt.Printf("\rProgress: %.1f%%", percent)
    }))

Function Categories / 함수 카테고리

1. File Reading / 파일 읽기 (8 functions / 8개 함수)
Function / 함수 Description / 설명
ReadFile(path string) ([]byte, error) Read entire file / 전체 파일 읽기
ReadString(path string) (string, error) Read file as string / 파일을 문자열로 읽기
ReadLines(path string) ([]string, error) Read file as lines / 파일을 줄로 읽기
ReadJSON(path string, v interface{}) error Read and unmarshal JSON / JSON 읽기 및 역직렬화
ReadYAML(path string, v interface{}) error Read and unmarshal YAML / YAML 읽기 및 역직렬화
ReadCSV(path string) ([][]string, error) Read CSV file / CSV 파일 읽기
ReadBytes(path string, offset, length int64) ([]byte, error) Read specific bytes / 특정 바이트 읽기
ReadChunk(path string, chunkSize int64, fn func([]byte) error) error Read file in chunks / 파일을 청크로 읽기
2. File Writing / 파일 쓰기 (11 functions / 11개 함수)
Function / 함수 Description / 설명
WriteFile(path string, data []byte) error Write bytes to file / 바이트를 파일에 쓰기
WriteString(path string, s string) error Write string to file / 문자열을 파일에 쓰기
WriteLines(path string, lines []string) error Write lines to file / 줄을 파일에 쓰기
WriteJSON(path string, v interface{}) error Marshal and write JSON / JSON 직렬화 및 쓰기
WriteYAML(path string, v interface{}) error Marshal and write YAML / YAML 직렬화 및 쓰기
WriteCSV(path string, records [][]string) error Write CSV file / CSV 파일 쓰기
WriteAtomic(path string, data []byte) error Atomic write (temp + rename) / 원자적 쓰기 (임시 + 이름 변경)
AppendFile(path string, data []byte) error Append bytes to file / 바이트를 파일에 추가
AppendString(path string, s string) error Append string to file / 문자열을 파일에 추가
AppendLines(path string, lines []string) error Append lines to file / 줄을 파일에 추가
AppendBytes(path string, data []byte) error Append bytes (alias) / 바이트 추가 (별칭)
3. File Copying / 파일 복사 (4 functions / 4개 함수)
Function / 함수 Description / 설명
CopyFile(src, dst string, opts ...CopyOption) error Copy single file / 단일 파일 복사
CopyDir(src, dst string, opts ...CopyOption) error Copy directory / 디렉토리 복사
CopyRecursive(src, dst string, opts ...CopyOption) error Copy recursively / 재귀적으로 복사
SyncDirs(src, dst string, opts ...CopyOption) error Sync two directories / 두 디렉토리 동기화

Copy Options / 복사 옵션:

  • WithOverwrite(bool) - Overwrite existing files / 기존 파일 덮어쓰기
  • WithPreservePermissions(bool) - Preserve file permissions / 파일 권한 보존
  • WithPreserveTimestamps(bool) - Preserve timestamps / 타임스탬프 보존
  • WithProgress(func(written, total int64)) - Progress callback / 진행 상황 콜백
  • WithFilter(func(path string, info os.FileInfo) bool) - File filter / 파일 필터
4. File Moving / 파일 이동 (5 functions / 5개 함수)
Function / 함수 Description / 설명
MoveFile(src, dst string) error Move file / 파일 이동
MoveDir(src, dst string) error Move directory / 디렉토리 이동
Rename(oldPath, newPath string) error Rename file/directory / 파일/디렉토리 이름 변경
RenameExt(path, newExt string) (string, error) Change file extension / 파일 확장자 변경
SafeMove(src, dst string) error Move with existence check / 존재 확인과 함께 이동
5. File Deleting / 파일 삭제 (7 functions / 7개 함수)
Function / 함수 Description / 설명
DeleteFile(path string) error Delete single file / 단일 파일 삭제
DeleteDir(path string) error Delete empty directory / 빈 디렉토리 삭제
DeleteRecursive(path string) error Delete recursively / 재귀적으로 삭제
DeletePattern(dir, pattern string) error Delete files by pattern / 패턴으로 파일 삭제
DeleteFiles(paths []string) error Delete multiple files / 여러 파일 삭제
Clean(path string) error Remove directory contents / 디렉토리 내용 제거
RemoveEmpty(path string) error Remove empty directories / 빈 디렉토리 제거
6. Directory Operations / 디렉토리 작업 (13 functions / 13개 함수)
Function / 함수 Description / 설명
MkdirAll(path string) error Create directory tree / 디렉토리 트리 생성
CreateTemp(dir, pattern string) (*os.File, error) Create temp file / 임시 파일 생성
CreateTempDir(dir, pattern string) (string, error) Create temp directory / 임시 디렉토리 생성
IsEmpty(path string) (bool, error) Check if directory is empty / 디렉토리가 비어 있는지 확인
DirSize(path string) (int64, error) Calculate directory size / 디렉토리 크기 계산
ListFiles(dir string) ([]string, error) List files only / 파일만 나열
ListDirs(dir string) ([]string, error) List directories only / 디렉토리만 나열
ListAll(dir string) ([]string, error) List all entries / 모든 항목 나열
Walk(root string, fn filepath.WalkFunc) error Walk directory tree / 디렉토리 트리 순회
WalkFiles(root string, fn func(string, os.FileInfo) error) error Walk files only / 파일만 순회
WalkDirs(root string, fn func(string, os.FileInfo) error) error Walk directories only / 디렉토리만 순회
FindFiles(root string, filter func(string, interface{}) bool) ([]string, error) Find files by filter / 필터로 파일 찾기
FilterFiles(root string, patterns []string) ([]string, error) Filter files by patterns / 패턴으로 파일 필터링
7. Path Operations / 경로 작업 (18 functions / 18개 함수)
Function / 함수 Description / 설명
Join(elem ...string) string Join path elements / 경로 요소 결합
Split(path string) (string, string) Split into dir and file / 디렉토리와 파일로 분할
Base(path string) string Get base name / 기본 이름 가져오기
Dir(path string) string Get directory / 디렉토리 가져오기
Ext(path string) string Get extension / 확장자 가져오기
Abs(path string) (string, error) Get absolute path / 절대 경로 가져오기
CleanPath(path string) string Clean path / 경로 정리
Normalize(path string) (string, error) Normalize path / 경로 정규화
ToSlash(path string) string Convert to forward slashes / 슬래시로 변환
FromSlash(path string) string Convert to OS-specific / OS 특정 변환
IsAbs(path string) bool Check if absolute / 절대 경로인지 확인
IsValid(path string) bool Validate path / 경로 검증
IsSafe(path, root string) bool Check path safety / 경로 안전성 확인
Match(pattern, name string) (bool, error) Match pattern / 패턴 매칭
Glob(pattern string) ([]string, error) Find by glob pattern / Glob 패턴으로 찾기
Rel(basepath, targpath string) (string, error) Get relative path / 상대 경로 가져오기
WithoutExt(path string) string Remove extension / 확장자 제거
ChangeExt(path, newExt string) string Change extension / 확장자 변경
HasExt(path string, exts ...string) bool Check extension / 확장자 확인
8. File Information / 파일 정보 (15 functions / 15개 함수)
Function / 함수 Description / 설명
Exists(path string) bool Check existence / 존재 확인
IsFile(path string) bool Check if file / 파일인지 확인
IsDir(path string) bool Check if directory / 디렉토리인지 확인
IsSymlink(path string) bool Check if symlink / 심볼릭 링크인지 확인
Size(path string) (int64, error) Get file size / 파일 크기 가져오기
SizeHuman(path string) (string, error) Get human-readable size / 사람이 읽기 쉬운 크기 가져오기
Chmod(path string, mode os.FileMode) error Change permissions / 권한 변경
Chown(path string, uid, gid int) error Change owner / 소유자 변경
IsReadable(path string) bool Check if readable / 읽기 가능한지 확인
IsWritable(path string) bool Check if writable / 쓰기 가능한지 확인
IsExecutable(path string) bool Check if executable / 실행 가능한지 확인
ModTime(path string) (time.Time, error) Get modification time / 수정 시간 가져오기
AccessTime(path string) (time.Time, error) Get access time / 접근 시간 가져오기
ChangeTime(path string) (time.Time, error) Get change time / 변경 시간 가져오기
Touch(path string) error Update modification time / 수정 시간 업데이트
9. File Hashing / 파일 해싱 (10 functions / 10개 함수)
Function / 함수 Description / 설명
MD5(path string) (string, error) Calculate MD5 hash / MD5 해시 계산
SHA1(path string) (string, error) Calculate SHA1 hash / SHA1 해시 계산
SHA256(path string) (string, error) Calculate SHA256 hash / SHA256 해시 계산
SHA512(path string) (string, error) Calculate SHA512 hash / SHA512 해시 계산
Hash(path, algorithm string) (string, error) Calculate hash by algorithm / 알고리즘별 해시 계산
HashBytes(data []byte, algorithm string) (string, error) Hash byte slice / 바이트 슬라이스 해시
CompareFiles(path1, path2 string) (bool, error) Compare files byte-by-byte / 파일을 바이트별로 비교
CompareHash(path1, path2 string) (bool, error) Compare files by hash / 해시로 파일 비교
Checksum(path string) (string, error) Calculate checksum (SHA256) / 체크섬 계산 (SHA256)
VerifyChecksum(path, expected string) (bool, error) Verify checksum / 체크섬 검증

Common Use Cases / 일반적인 사용 사례

1. Safe File Writing / 안전한 파일 쓰기
// Automatically creates parent directories / 자동으로 상위 디렉토리 생성
err := fileutil.WriteString("deep/nested/path/file.txt", "content")
2. JSON/YAML Configuration / JSON/YAML 설정
// Read config / 설정 읽기
var config Config
err := fileutil.ReadJSON("config.json", &config)

// Write config / 설정 쓰기
err = fileutil.WriteJSON("config.json", config)
3. File Backup / 파일 백업
// Copy with timestamp / 타임스탬프와 함께 복사
timestamp := time.Now().Format("20060102-150405")
backupPath := fileutil.ChangeExt("file.txt", "."+timestamp+".bak")
err := fileutil.CopyFile("file.txt", backupPath)
4. Safe File Update / 안전한 파일 업데이트
// Atomic write (writes to temp file, then renames) / 원자적 쓰기 (임시 파일에 쓰기, 그 다음 이름 변경)
err := fileutil.WriteAtomic("important-data.json", data)
5. File Integrity Check / 파일 무결성 확인
// Generate checksum / 체크섬 생성
checksum, err := fileutil.Checksum("file.dat")

// Later, verify / 나중에 검증
valid, err := fileutil.VerifyChecksum("file.dat", checksum)
if !valid {
    log.Println("File has been modified!")
}
// Find all Go files / 모든 Go 파일 찾기
goFiles, err := fileutil.FindFiles(".", func(path string, info interface{}) bool {
    return fileutil.Ext(path) == ".go"
})

for _, file := range goFiles {
    fmt.Println(file)
}
7. Large File Processing / 대용량 파일 처리
// Process file in chunks / 파일을 청크로 처리
err := fileutil.ReadChunk("large-file.dat", 1024*1024, func(chunk []byte) error {
    // Process each 1MB chunk / 각 1MB 청크 처리
    return processChunk(chunk)
})

Best Practices / 모범 사례

1. Always Check Errors / 항상 에러 확인
// Good / 좋음
content, err := fileutil.ReadString("file.txt")
if err != nil {
    log.Printf("Failed to read file: %v", err)
    return err
}

// Bad / 나쁨
content, _ := fileutil.ReadString("file.txt")
2. Use Atomic Writes for Critical Data / 중요한 데이터에 원자적 쓰기 사용
// For important data, use atomic writes / 중요한 데이터의 경우 원자적 쓰기 사용
err := fileutil.WriteAtomic("database.json", data)
3. Verify File Existence Before Operations / 작업 전 파일 존재 확인
if !fileutil.Exists("input.txt") {
    return fmt.Errorf("input file does not exist")
}
4. Use Progress Callbacks for Large Operations / 대용량 작업에 진행 상황 콜백 사용
err := fileutil.CopyFile("large-file.iso", "backup.iso",
    fileutil.WithProgress(func(written, total int64) {
        percent := float64(written) / float64(total) * 100
        fmt.Printf("\rCopying: %.1f%%", percent)
    }))
5. Clean Up Temporary Files / 임시 파일 정리
tempFile, err := fileutil.CreateTemp("", "myapp-*")
if err != nil {
    return err
}
defer os.Remove(tempFile.Name()) // Clean up / 정리
6. Use Path Functions for Cross-Platform Compatibility / 크로스 플랫폼 호환성을 위해 경로 함수 사용
// Good / 좋음
path := fileutil.Join("home", "user", "file.txt")

// Bad / 나쁨
path := "home/user/file.txt" // Unix-specific / Unix 전용
7. Validate Paths for Security / 보안을 위해 경로 검증
// Check if path is safe (no directory traversal) / 경로가 안전한지 확인 (디렉토리 탐색 없음)
if !fileutil.IsSafe(userPath, rootDir) {
    return fmt.Errorf("unsafe path: %s", userPath)
}

Error Handling / 에러 처리

The package provides custom error types for common scenarios:

패키지는 일반적인 시나리오에 대한 사용자 정의 에러 타입을 제공합니다:

_, err := fileutil.ReadString("missing.txt")
if fileutil.IsNotFound(err) {
    // File doesn't exist / 파일이 존재하지 않음
}

_, err = fileutil.ReadString("/root/secure.txt")
if fileutil.IsPermission(err) {
    // Permission denied / 권한 거부
}

err = fileutil.WriteString("existing.txt", "data")
if fileutil.IsExist(err) {
    // File already exists / 파일이 이미 존재함
}

Performance Considerations / 성능 고려사항

1. Buffered I/O / 버퍼링된 I/O

All file operations use buffered I/O with a default buffer size of 32KB for optimal performance.

모든 파일 작업은 최적의 성능을 위해 기본 버퍼 크기 32KB의 버퍼링된 I/O를 사용합니다.

2. Large Files / 대용량 파일

For large files, use ReadChunk to process data in chunks:

대용량 파일의 경우 ReadChunk를 사용하여 데이터를 청크로 처리합니다:

// Process 1MB at a time / 한 번에 1MB 처리
err := fileutil.ReadChunk("huge-file.dat", fileutil.DefaultChunkSize, func(chunk []byte) error {
    return process(chunk)
})
3. Directory Operations / 디렉토리 작업

For recursive operations on large directory trees, use Walk functions:

대규모 디렉토리 트리의 재귀 작업의 경우 Walk 함수를 사용합니다:

// More efficient than ListFiles for large directories / 대규모 디렉토리에는 ListFiles보다 효율적
err := fileutil.WalkFiles(".", func(path string, info os.FileInfo) error {
    // Process each file / 각 파일 처리
    return nil
})

Comprehensive Documentation / 종합 문서

For more detailed information, please refer to:

더 자세한 정보는 다음을 참조하세요:

  • User Manual - Complete usage guide with examples / 예제가 포함된 완전한 사용 가이드
  • Developer Guide - Architecture and implementation details / 아키텍처 및 구현 세부사항
  • Examples - Comprehensive code examples / 종합적인 코드 예제

Version / 버전

Current version: v1.9.001

현재 버전: v1.9.001

License / 라이선스

MIT License - see LICENSE file for details

MIT 라이선스 - 자세한 내용은 LICENSE 파일 참조

Contributing / 기여

Contributions are welcome! Please see the Developer Guide for guidelines.

기여를 환영합니다! 가이드라인은 Developer Guide를 참조하세요.

Support / 지원


Made with ❤️ for the Go community / Go 커뮤니티를 위해 ❤️로 만들었습니다

Documentation

Overview

Package fileutil provides extreme simplicity file and path utilities for Golang. Package fileutil은 Golang을 위한 극도로 간단한 파일 및 경로 유틸리티를 제공합니다.

This package reduces 20+ lines of repetitive file manipulation code to just 1-2 lines. 이 패키지는 20줄 이상의 반복적인 파일 조작 코드를 단 1-2줄로 줄입니다.

Features 특징: - Safe file operations with automatic directory creation 자동 디렉토리 생성을 사용한 안전한 파일 작업 - Cross-platform compatibility 크로스 플랫폼 호환성 - Comprehensive file/directory operations 포괄적인 파일/디렉토리 작업 - Path manipulation and validation 경로 조작 및 검증 - File hashing and checksums 파일 해싱 및 체크섬 - File compression (zip, tar, gzip) 파일 압축 (zip, tar, gzip) - Temporary file management 임시 파일 관리 - Zero external dependencies (except yaml) 외부 의존성 없음 (yaml 제외)

Example 예제:

// Write file with automatic directory creation 자동 디렉토리 생성과 함께 파일 쓰기

err := fileutil.WriteString("path/to/file.txt", "Hello, World!")

// Read file 파일 읽기

content, err := fileutil.ReadString("path/to/file.txt")

// Copy file 파일 복사

err = fileutil.CopyFile("source.txt", "destination.txt")

// List all .go files recursively 모든 .go 파일 재귀적으로 나열

files, err := fileutil.FindFiles(".", func(path string, info os.FileInfo) bool {
    return filepath.Ext(path) == ".go"
})

Version information is loaded dynamically from cfg/app.yaml. 버전 정보는 cfg/app.yaml에서 동적으로 로드됩니다.

Index

Constants

View Source
const (
	// DefaultFileMode is the default file permission (rw-r--r--)
	// DefaultFileMode는 기본 파일 권한입니다 (rw-r--r--)
	DefaultFileMode os.FileMode = 0644

	// DefaultDirMode is the default directory permission (rwxr-xr-x)
	// DefaultDirMode는 기본 디렉토리 권한입니다 (rwxr-xr-x)
	DefaultDirMode os.FileMode = 0755

	// DefaultExecMode is the default executable file permission (rwxr-xr-x)
	// DefaultExecMode는 기본 실행 파일 권한입니다 (rwxr-xr-x)
	DefaultExecMode os.FileMode = 0755
)

Default file and directory permissions 기본 파일 및 디렉토리 권한

View Source
const (
	// DefaultBufferSize is the default buffer size for reading/writing (32KB)
	// DefaultBufferSize는 읽기/쓰기를 위한 기본 버퍼 크기입니다 (32KB)
	DefaultBufferSize = 32 * 1024

	// DefaultChunkSize is the default chunk size for streaming operations (1MB)
	// DefaultChunkSize는 스트리밍 작업을 위한 기본 청크 크기입니다 (1MB)
	DefaultChunkSize = 1024 * 1024
)

Buffer sizes for I/O operations I/O 작업을 위한 버퍼 크기

View Source
const (
	KB = 1024
	MB = 1024 * KB
	GB = 1024 * MB
	TB = 1024 * GB
)

Size units for human-readable file sizes 사람이 읽기 쉬운 파일 크기를 위한 크기 단위

Variables

View Source
var (
	// ErrNotFound indicates that the file or directory was not found
	// ErrNotFound는 파일 또는 디렉토리를 찾을 수 없음을 나타냅니다
	ErrNotFound = errors.New("fileutil: file or directory not found")

	// ErrNotFile indicates that the path is not a regular file
	// ErrNotFile은 경로가 일반 파일이 아님을 나타냅니다
	ErrNotFile = errors.New("fileutil: not a regular file")

	// ErrNotDirectory indicates that the path is not a directory
	// ErrNotDirectory는 경로가 디렉토리가 아님을 나타냅니다
	ErrNotDirectory = errors.New("fileutil: not a directory")

	// ErrPermission indicates a permission denied error
	// ErrPermission은 권한 거부 에러를 나타냅니다
	ErrPermission = errors.New("fileutil: permission denied")

	// ErrInvalidPath indicates that the path is invalid or unsafe
	// ErrInvalidPath는 경로가 유효하지 않거나 안전하지 않음을 나타냅니다
	ErrInvalidPath = errors.New("fileutil: invalid or unsafe path")

	// ErrAlreadyExists indicates that the file or directory already exists
	// ErrAlreadyExists는 파일 또는 디렉토리가 이미 존재함을 나타냅니다
	ErrAlreadyExists = errors.New("fileutil: file or directory already exists")

	// ErrIsDirectory indicates that the operation cannot be performed on a directory
	// ErrIsDirectory는 디렉토리에서 작업을 수행할 수 없음을 나타냅니다
	ErrIsDirectory = errors.New("fileutil: is a directory")

	// ErrNotEmpty indicates that the directory is not empty
	// ErrNotEmpty는 디렉토리가 비어 있지 않음을 나타냅니다
	ErrNotEmpty = errors.New("fileutil: directory not empty")

	// ErrInvalidFormat indicates an invalid file format
	// ErrInvalidFormat은 유효하지 않은 파일 형식을 나타냅니다
	ErrInvalidFormat = errors.New("fileutil: invalid file format")

	// ErrInvalidChecksum indicates that the checksum verification failed
	// ErrInvalidChecksum은 체크섬 검증 실패를 나타냅니다
	ErrInvalidChecksum = errors.New("fileutil: invalid checksum")
)

Common errors 일반적인 에러

View Source
var Version = version.Get()

Version is the current version of the fileutil package Version은 fileutil 패키지의 현재 버전입니다

Functions

func Abs

func Abs(path string) (string, error)

Abs returns the absolute path of a file or directory Abs는 파일 또는 디렉토리의 절대 경로를 반환합니다

Example 예제:

abs, err := fileutil.Abs("relative/path/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Println(abs) // "/current/dir/relative/path/file.txt"

func AccessTime

func AccessTime(path string) (time.Time, error)

AccessTime returns the access time of a file or directory AccessTime은 파일 또는 디렉토리의 액세스 시간을 반환합니다

Note: This function is platform-specific and may not work on all systems. 참고: 이 함수는 플랫폼별로 다르며 모든 시스템에서 작동하지 않을 수 있습니다.

Example 예제:

accessTime, err := fileutil.AccessTime("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Last accessed: %s\n", accessTime)

func AppendBytes

func AppendBytes(path string, data []byte) error

AppendBytes is an alias for AppendFile AppendBytes는 AppendFile의 별칭입니다

func AppendFile

func AppendFile(path string, data []byte) error

AppendFile appends data to a file, creating it if it doesn't exist AppendFile은 파일에 데이터를 추가하고, 파일이 존재하지 않으면 생성합니다

Example 예제:

err := fileutil.AppendFile("log.txt", []byte("New log entry\n"))
if err != nil {
    log.Fatal(err)
}

func AppendLines

func AppendLines(path string, lines []string) error

AppendLines appends lines to a file, creating it if it doesn't exist AppendLines는 파일에 줄을 추가하고, 파일이 존재하지 않으면 생성합니다

Example 예제:

lines := []string{"Line 1", "Line 2", "Line 3"}
err := fileutil.AppendLines("log.txt", lines)
if err != nil {
    log.Fatal(err)
}

func AppendString

func AppendString(path string, content string) error

AppendString appends a string to a file, creating it if it doesn't exist AppendString은 파일에 문자열을 추가하고, 파일이 존재하지 않으면 생성합니다

Example 예제:

err := fileutil.AppendString("log.txt", "New log entry\n")
if err != nil {
    log.Fatal(err)
}

func Base

func Base(path string) string

Base returns the last element of a path Base는 경로의 마지막 요소를 반환합니다

This is an alias for filepath.Base. 이는 filepath.Base의 별칭입니다.

Example 예제:

base := fileutil.Base("path/to/file.txt")
// Result: "file.txt"

func ChangeExt

func ChangeExt(path, newExt string) string

ChangeExt changes the file extension ChangeExt는 파일 확장자를 변경합니다

Example 예제:

path := fileutil.ChangeExt("file.txt", ".md")
// Result: "file.md"

func ChangeTime

func ChangeTime(path string) (time.Time, error)

ChangeTime returns the change time of a file or directory ChangeTime은 파일 또는 디렉토리의 변경 시간을 반환합니다

Note: This function is platform-specific and may not work on all systems. 참고: 이 함수는 플랫폼별로 다르며 모든 시스템에서 작동하지 않을 수 있습니다.

Example 예제:

changeTime, err := fileutil.ChangeTime("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Last changed: %s\n", changeTime)

func Checksum

func Checksum(path string) (string, error)

Checksum calculates the SHA256 checksum of a file Checksum은 파일의 SHA256 체크섬을 계산합니다

This is an alias for SHA256. 이는 SHA256의 별칭입니다.

Example 예제:

checksum, err := fileutil.Checksum("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Println("Checksum:", checksum)

func Chmod

func Chmod(path string, mode os.FileMode) error

Chmod changes the mode of a file or directory Chmod는 파일 또는 디렉토리의 모드를 변경합니다

Example 예제:

err := fileutil.Chmod("path/to/file.txt", 0644)
if err != nil {
    log.Fatal(err)
}

func Chown

func Chown(path string, uid, gid int) error

Chown changes the owner and group of a file or directory Chown은 파일 또는 디렉토리의 소유자와 그룹을 변경합니다

Example 예제:

err := fileutil.Chown("path/to/file.txt", 1000, 1000)
if err != nil {
    log.Fatal(err)
}

func Clean

func Clean(path string) error

Clean removes all files and subdirectories in a directory but keeps the directory itself Clean은 디렉토리의 모든 파일과 하위 디렉토리를 제거하지만 디렉토리 자체는 유지합니다

Example 예제:

err := fileutil.Clean("path/to/directory")
if err != nil {
    log.Fatal(err)
}

func CleanPath

func CleanPath(path string) string

CleanPath cleans a path by simplifying it CleanPath는 경로를 단순화하여 정리합니다

This is an alias for filepath.Clean. 이는 filepath.Clean의 별칭입니다.

Example 예제:

clean := fileutil.CleanPath("path/to/../file.txt")
// Result: "path/file.txt"

func CompareFiles

func CompareFiles(path1, path2 string) (bool, error)

CompareFiles compares two files byte by byte CompareFiles는 두 파일을 바이트 단위로 비교합니다

Returns true if the files are identical, false otherwise. 파일이 동일하면 true를, 그렇지 않으면 false를 반환합니다.

Example 예제:

same, err := fileutil.CompareFiles("file1.txt", "file2.txt")
if err != nil {
    log.Fatal(err)
}
if same {
    fmt.Println("Files are identical")
}

func CompareHash

func CompareHash(path1, path2 string) (bool, error)

CompareHash compares two files by comparing their SHA256 hashes CompareHash는 두 파일의 SHA256 해시를 비교하여 파일을 비교합니다

This is faster than byte-by-byte comparison for large files. 이는 큰 파일에 대해 바이트 단위 비교보다 빠릅니다.

Example 예제:

same, err := fileutil.CompareHash("file1.txt", "file2.txt")
if err != nil {
    log.Fatal(err)
}
if same {
    fmt.Println("Files have the same hash")
}

func CopyDir

func CopyDir(src, dst string, options ...CopyOption) error

CopyDir copies a directory from src to dst with optional settings CopyDir는 선택적 설정을 사용하여 src에서 dst로 디렉토리를 복사합니다

Example 예제:

// Copy directory 디렉토리 복사

err := fileutil.CopyDir("source-dir", "destination-dir")

// Copy with filter (exclude hidden files) 필터와 함께 복사 (숨겨진 파일 제외)

err = fileutil.CopyDir("source-dir", "destination-dir",
    fileutil.WithFilter(func(path string, info os.FileInfo) bool {
        return !strings.HasPrefix(info.Name(), ".")
    }))

func CopyFile

func CopyFile(src, dst string, options ...CopyOption) error

CopyFile copies a file from src to dst with optional settings CopyFile은 선택적 설정을 사용하여 src에서 dst로 파일을 복사합니다

Example 예제:

// Simple copy 간단한 복사

err := fileutil.CopyFile("source.txt", "destination.txt")

// Copy with overwrite 덮어쓰기와 함께 복사

err = fileutil.CopyFile("source.txt", "destination.txt",
    fileutil.WithOverwrite(true))

// Copy with progress callback 진행 상황 콜백과 함께 복사

err = fileutil.CopyFile("source.txt", "destination.txt",
    fileutil.WithProgress(func(written, total int64) {
        fmt.Printf("Progress: %d/%d (%.2f%%)\n",
            written, total, float64(written)/float64(total)*100)
    }))

func CopyRecursive

func CopyRecursive(src, dst string, options ...CopyOption) error

CopyRecursive is an alias for CopyDir CopyRecursive는 CopyDir의 별칭입니다

func CreateFile

func CreateFile(path string, perm ...os.FileMode) (*os.File, error)

WriteStream writes data to a file using buffered I/O WriteStream은 버퍼링된 I/O를 사용하여 파일에 데이터를 씁니다

This is useful for writing large amounts of data efficiently. 이는 대량의 데이터를 효율적으로 쓰는 데 유용합니다.

Example 예제:

file, err := fileutil.CreateFile("large-file.txt")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

writer := bufio.NewWriter(file)
for _, line := range lines {
    writer.WriteString(line + "\n")
}
writer.Flush()

func CreateTemp

func CreateTemp(dir, pattern string) (string, error)

CreateTemp creates a temporary file in the specified directory CreateTemp는 지정된 디렉토리에 임시 파일을 생성합니다

Example 예제:

tempPath, err := fileutil.CreateTemp("", "temp-*.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Println("Temp file:", tempPath)

func CreateTempDir

func CreateTempDir(dir, pattern string) (string, error)

CreateTempDir creates a temporary directory in the specified directory CreateTempDir는 지정된 디렉토리에 임시 디렉토리를 생성합니다

Example 예제:

tempDir, err := fileutil.CreateTempDir("", "temp-dir-*")
if err != nil {
    log.Fatal(err)
}
fmt.Println("Temp directory:", tempDir)

func DeleteDir

func DeleteDir(path string) error

DeleteDir deletes an empty directory DeleteDir는 빈 디렉토리를 삭제합니다

Example 예제:

err := fileutil.DeleteDir("path/to/empty-dir")
if err != nil {
    log.Fatal(err)
}

func DeleteFile

func DeleteFile(path string) error

DeleteFile deletes a file DeleteFile은 파일을 삭제합니다

Example 예제:

err := fileutil.DeleteFile("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}

func DeleteFiles

func DeleteFiles(paths ...string) error

DeleteFiles deletes multiple files DeleteFiles는 여러 파일을 삭제합니다

Example 예제:

err := fileutil.DeleteFiles("file1.txt", "file2.txt", "file3.txt")
if err != nil {
    log.Fatal(err)
}

func DeletePattern

func DeletePattern(pattern string) error

DeletePattern deletes all files matching a glob pattern DeletePattern은 glob 패턴과 일치하는 모든 파일을 삭제합니다

Example 예제:

// Delete all .tmp files 모든 .tmp 파일 삭제

err := fileutil.DeletePattern("*.tmp")
if err != nil {
    log.Fatal(err)
}

func DeleteRecursive

func DeleteRecursive(path string) error

DeleteRecursive deletes a file or directory recursively DeleteRecursive는 파일 또는 디렉토리를 재귀적으로 삭제합니다

This is an alias for os.RemoveAll. 이는 os.RemoveAll의 별칭입니다.

Example 예제:

err := fileutil.DeleteRecursive("path/to/directory")
if err != nil {
    log.Fatal(err)
}

func Dir

func Dir(path string) string

Dir returns the directory part of a path Dir는 경로의 디렉토리 부분을 반환합니다

This is an alias for filepath.Dir. 이는 filepath.Dir의 별칭입니다.

Example 예제:

dir := fileutil.Dir("path/to/file.txt")
// Result: "path/to"

func DirSize

func DirSize(path string) (int64, error)

DirSize calculates the total size of all files in a directory recursively DirSize는 디렉토리의 모든 파일 크기를 재귀적으로 계산합니다

Example 예제:

size, err := fileutil.DirSize("path/to/directory")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Directory size: %d bytes\n", size)

func Exists

func Exists(path string) bool

Exists checks if a file or directory exists Exists는 파일 또는 디렉토리가 존재하는지 확인합니다

Example 예제:

if fileutil.Exists("path/to/file.txt") {
    fmt.Println("File exists")
}

func Ext

func Ext(path string) string

Ext returns the file extension of a path Ext는 경로의 파일 확장자를 반환합니다

This is an alias for filepath.Ext. 이는 filepath.Ext의 별칭입니다.

Example 예제:

ext := fileutil.Ext("file.txt")
// Result: ".txt"

func FileInfo

func FileInfo(path string) (os.FileInfo, error)

FileInfo returns the FileInfo for a file or directory FileInfo는 파일 또는 디렉토리의 FileInfo를 반환합니다

This is an alias for os.Stat. 이는 os.Stat의 별칭입니다.

Example 예제:

info, err := fileutil.FileInfo("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Name: %s, Size: %d\n", info.Name(), info.Size())

func FilterFiles

func FilterFiles(files []string, predicate func(path string) bool) ([]string, error)

FilterFiles filters a slice of file paths using a predicate function FilterFiles는 조건자 함수를 사용하여 파일 경로 슬라이스를 필터링합니다

Example 예제:

// Filter large files (>1MB) 큰 파일 필터링 (>1MB)

large, err := fileutil.FilterFiles(files, func(path string) bool {
    info, _ := os.Stat(path)
    return info.Size() > 1024*1024
})

func FindFiles

func FindFiles(root string, predicate func(path string, info os.FileInfo) bool) ([]string, error)

FindFiles finds all files matching a predicate function FindFiles는 조건자 함수와 일치하는 모든 파일을 찾습니다

Example 예제:

// Find all .go files 모든 .go 파일 찾기

files, err := fileutil.FindFiles(".", func(path string, info os.FileInfo) bool {
    return filepath.Ext(path) == ".go"
})

func FromSlash

func FromSlash(path string) string

FromSlash converts a path from forward slashes to OS-specific separators FromSlash는 경로를 슬래시에서 OS별 구분자로 변환합니다

This is an alias for filepath.FromSlash. 이는 filepath.FromSlash의 별칭입니다.

Example 예제:

osPath := fileutil.FromSlash("path/to/file.txt")
// Result: "path/to/file.txt" (on Unix)
// Result: "path\\to\\file.txt" (on Windows)

func Glob

func Glob(pattern string) ([]string, error)

Glob returns all files matching a pattern Glob는 패턴과 일치하는 모든 파일을 반환합니다

This is an alias for filepath.Glob. 이는 filepath.Glob의 별칭입니다.

Example 예제:

files, err := fileutil.Glob("*.txt")
if err != nil {
    log.Fatal(err)
}
for _, file := range files {
    fmt.Println(file)
}

func HasExt

func HasExt(path string, exts ...string) bool

HasExt checks if a path has one of the specified extensions HasExt는 경로가 지정된 확장자 중 하나를 가지고 있는지 확인합니다

Example 예제:

if fileutil.HasExt("file.txt", ".txt", ".md") {
    fmt.Println("File has a valid extension")
}

func Hash

func Hash(path string, algorithm string) (string, error)

Hash calculates the hash of a file using the specified algorithm Hash는 지정된 알고리즘을 사용하여 파일의 해시를 계산합니다

Supported algorithms: md5, sha1, sha256, sha512 지원되는 알고리즘: md5, sha1, sha256, sha512

Example 예제:

hash, err := fileutil.Hash("path/to/file.txt", "sha256")
if err != nil {
    log.Fatal(err)
}
fmt.Println("Hash:", hash)

func HashBytes

func HashBytes(path string) ([]byte, error)

HashBytes calculates the hash of a file and returns it as a byte slice HashBytes는 파일의 해시를 계산하고 바이트 슬라이스로 반환합니다

This is useful when you need the raw hash bytes instead of a hex string. 이는 16진수 문자열 대신 원시 해시 바이트가 필요할 때 유용합니다.

Example 예제:

hashBytes, err := fileutil.HashBytes("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}

func HashDir

func HashDir(path string) (string, error)

HashDir calculates the combined hash of all files in a directory HashDir는 디렉토리의 모든 파일의 결합된 해시를 계산합니다

This is useful for detecting changes in a directory. 이는 디렉토리의 변경 사항을 감지하는 데 유용합니다.

Example 예제:

hash, err := fileutil.HashDir("path/to/directory")
if err != nil {
    log.Fatal(err)
}
fmt.Println("Directory hash:", hash)

func IsAbs

func IsAbs(path string) bool

IsAbs checks if a path is absolute IsAbs는 경로가 절대 경로인지 확인합니다

This is an alias for filepath.IsAbs. 이는 filepath.IsAbs의 별칭입니다.

Example 예제:

if fileutil.IsAbs("/absolute/path") {
    fmt.Println("Path is absolute")
}

func IsDir

func IsDir(path string) bool

IsDir checks if the path is a directory IsDir는 경로가 디렉토리인지 확인합니다

Example 예제:

if fileutil.IsDir("path/to/directory") {
    fmt.Println("Is a directory")
}

func IsEmpty

func IsEmpty(path string) (bool, error)

IsEmpty checks if a directory is empty IsEmpty는 디렉토리가 비어 있는지 확인합니다

Example 예제:

empty, err := fileutil.IsEmpty("path/to/directory")
if err != nil {
    log.Fatal(err)
}
if empty {
    fmt.Println("Directory is empty")
}

func IsExecutable

func IsExecutable(path string) bool

IsExecutable checks if a file is executable IsExecutable은 파일이 실행 가능한지 확인합니다

Example 예제:

if fileutil.IsExecutable("path/to/script.sh") {
    fmt.Println("File is executable")
}

func IsExist

func IsExist(err error) bool

IsExist checks if the error is an "already exists" error IsExist는 에러가 "이미 존재함" 에러인지 확인합니다

Example 예제:

if fileutil.IsExist(err) { Handle already exists 이미 존재함 처리

}

func IsFile

func IsFile(path string) bool

IsFile checks if the path is a regular file IsFile은 경로가 일반 파일인지 확인합니다

Example 예제:

if fileutil.IsFile("path/to/file.txt") {
    fmt.Println("Is a file")
}

func IsInvalid

func IsInvalid(err error) bool

IsInvalid checks if the error is an "invalid path" error IsInvalid는 에러가 "유효하지 않은 경로" 에러인지 확인합니다

Example 예제:

if fileutil.IsInvalid(err) { Handle invalid path 유효하지 않은 경로 처리

}

func IsNotFound

func IsNotFound(err error) bool

IsNotFound checks if the error is a "file not found" error IsNotFound는 에러가 "파일을 찾을 수 없음" 에러인지 확인합니다

Example 예제:

if fileutil.IsNotFound(err) { Handle file not found 파일을 찾을 수 없음 처리

}

func IsPermission

func IsPermission(err error) bool

IsPermission checks if the error is a "permission denied" error IsPermission은 에러가 "권한 거부됨" 에러인지 확인합니다

Example 예제:

if fileutil.IsPermission(err) { Handle permission denied 권한 거부됨 처리

}

func IsReadable

func IsReadable(path string) bool

IsReadable checks if a file or directory is readable IsReadable은 파일 또는 디렉토리가 읽기 가능한지 확인합니다

Example 예제:

if fileutil.IsReadable("path/to/file.txt") {
    fmt.Println("File is readable")
}

func IsSafe

func IsSafe(path, root string) bool

IsSafe checks if a path is safe (no path traversal attempts) IsSafe는 경로가 안전한지 확인합니다 (경로 순회 시도 없음)

This function checks if the path contains ".." or absolute paths outside the root. 이 함수는 경로에 ".."가 포함되어 있거나 루트 외부의 절대 경로가 있는지 확인합니다.

Example 예제:

if fileutil.IsSafe("path/to/file.txt", "/root/dir") {
    fmt.Println("Path is safe")
}
func IsSymlink(path string) bool

IsSymlink checks if the path is a symbolic link IsSymlink은 경로가 심볼릭 링크인지 확인합니다

Example 예제:

if fileutil.IsSymlink("path/to/link") {
    fmt.Println("Is a symbolic link")
}

func IsValid

func IsValid(path string) bool

IsValid checks if a path is valid (not empty and contains no invalid characters) IsValid는 경로가 유효한지 확인합니다 (비어 있지 않고 유효하지 않은 문자를 포함하지 않음)

Example 예제:

if fileutil.IsValid("path/to/file.txt") {
    fmt.Println("Path is valid")
}

func IsWritable

func IsWritable(path string) bool

IsWritable checks if a file or directory is writable IsWritable은 파일 또는 디렉토리가 쓰기 가능한지 확인합니다

Example 예제:

if fileutil.IsWritable("path/to/file.txt") {
    fmt.Println("File is writable")
}

func Join

func Join(elem ...string) string

Join joins path elements into a single path using the OS-specific separator Join은 OS별 구분자를 사용하여 경로 요소를 단일 경로로 결합합니다

This is an alias for filepath.Join. 이는 filepath.Join의 별칭입니다.

Example 예제:

path := fileutil.Join("home", "user", "documents", "file.txt")
// Result: "home/user/documents/file.txt" (on Unix)
// Result: "home\\user\\documents\\file.txt" (on Windows)

func ListAll

func ListAll(dir string, recursive ...bool) ([]string, error)

ListAll lists all files and directories ListAll은 모든 파일과 디렉토리를 나열합니다

If recursive is true, it lists all entries recursively. recursive가 true이면 모든 항목을 재귀적으로 나열합니다.

Example 예제:

// List all entries in current directory only 현재 디렉토리의 모든 항목만 나열

entries, err := fileutil.ListAll(".")

// List all entries recursively 재귀적으로 모든 항목 나열

entries, err = fileutil.ListAll(".", true)

func ListDirs

func ListDirs(dir string, recursive ...bool) ([]string, error)

ListDirs lists all subdirectories in a directory ListDirs는 디렉토리의 모든 하위 디렉토리를 나열합니다

If recursive is true, it lists all subdirectories recursively. recursive가 true이면 모든 하위 디렉토리를 재귀적으로 나열합니다.

Example 예제:

// List subdirectories in current directory only 현재 디렉토리의 하위 디렉토리만 나열

dirs, err := fileutil.ListDirs(".")

// List subdirectories recursively 재귀적으로 하위 디렉토리 나열

dirs, err = fileutil.ListDirs(".", true)

func ListFiles

func ListFiles(dir string, recursive ...bool) ([]string, error)

ListFiles lists all files in a directory ListFiles는 디렉토리의 모든 파일을 나열합니다

If recursive is true, it lists files in all subdirectories. recursive가 true이면 모든 하위 디렉토리의 파일을 나열합니다.

Example 예제:

// List files in current directory only 현재 디렉토리의 파일만 나열

files, err := fileutil.ListFiles(".")

// List files recursively 재귀적으로 파일 나열

files, err = fileutil.ListFiles(".", true)

func Lstat

func Lstat(path string) (os.FileInfo, error)

Lstat returns the FileInfo for a file or directory (does not follow symbolic links) Lstat은 파일 또는 디렉토리의 FileInfo를 반환합니다 (심볼릭 링크를 따라가지 않음)

Example 예제:

info, err := fileutil.Lstat("path/to/link")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Name: %s, Size: %d\n", info.Name(), info.Size())

func MD5

func MD5(path string) (string, error)

MD5 calculates the MD5 hash of a file MD5는 파일의 MD5 해시를 계산합니다

Example 예제:

hash, err := fileutil.MD5("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Println("MD5:", hash)

func Match

func Match(pattern, name string) (bool, error)

Match checks if a filename matches a pattern Match는 파일 이름이 패턴과 일치하는지 확인합니다

This is an alias for filepath.Match. 이는 filepath.Match의 별칭입니다.

Example 예제:

matched, err := fileutil.Match("*.txt", "file.txt")
if err != nil {
    log.Fatal(err)
}
if matched {
    fmt.Println("File matches pattern")
}

func MkdirAll

func MkdirAll(path string, perm ...os.FileMode) error

MkdirAll creates a directory and all necessary parents MkdirAll은 디렉토리와 모든 필요한 부모 디렉토리를 생성합니다

Example 예제:

err := fileutil.MkdirAll("path/to/nested/directory")
if err != nil {
    log.Fatal(err)
}

func ModTime

func ModTime(path string) (time.Time, error)

ModTime returns the modification time of a file or directory ModTime은 파일 또는 디렉토리의 수정 시간을 반환합니다

Example 예제:

modTime, err := fileutil.ModTime("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Last modified: %s\n", modTime)

func MoveDir

func MoveDir(src, dst string) error

MoveDir moves a directory from src to dst MoveDir는 src에서 dst로 디렉토리를 이동합니다

Example 예제:

err := fileutil.MoveDir("old-path/dir", "new-path/dir")
if err != nil {
    log.Fatal(err)
}

func MoveFile

func MoveFile(src, dst string) error

MoveFile moves a file from src to dst MoveFile은 src에서 dst로 파일을 이동합니다

Example 예제:

err := fileutil.MoveFile("old-path/file.txt", "new-path/file.txt")
if err != nil {
    log.Fatal(err)
}

func NewWriter

func NewWriter(path string, perm ...os.FileMode) (*bufio.Writer, *os.File, error)

NewWriter creates a new buffered writer for the specified file NewWriter는 지정된 파일에 대한 새 버퍼링된 writer를 생성합니다

Example 예제:

writer, file, err := fileutil.NewWriter("output.txt")
if err != nil {
    log.Fatal(err)
}
defer file.Close()
defer writer.Flush()

for _, line := range lines {
    writer.WriteString(line + "\n")
}

func Normalize

func Normalize(path string) (string, error)

Normalize normalizes a path by cleaning it and making it absolute if possible Normalize는 경로를 정리하고 가능하면 절대 경로로 만들어 정규화합니다

Example 예제:

normalized, err := fileutil.Normalize("./path/../file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Println(normalized) // "/current/dir/file.txt"

func ReadBytes

func ReadBytes(path string, offset, size int64) ([]byte, error)

ReadBytes reads a specific number of bytes from a file at a given offset ReadBytes는 주어진 오프셋에서 파일로부터 특정 바이트 수를 읽습니다

Example 예제:

// Read 100 bytes starting from offset 1000
data, err := fileutil.ReadBytes("large-file.bin", 1000, 100)
if err != nil {
    log.Fatal(err)
}

func ReadCSV

func ReadCSV(path string) ([][]string, error)

ReadCSV reads a CSV file and returns its contents as a slice of string slices ReadCSV는 CSV 파일을 읽고 내용을 문자열 슬라이스의 슬라이스로 반환합니다

Example 예제:

records, err := fileutil.ReadCSV("data.csv")
if err != nil {
    log.Fatal(err)
}
for _, record := range records {
    fmt.Println(record)
}

func ReadChunk

func ReadChunk(path string, chunkSize int64, fn func([]byte) error) error

ReadChunk reads a file in chunks and calls the provided function for each chunk ReadChunk는 파일을 청크 단위로 읽고 각 청크마다 제공된 함수를 호출합니다

This is useful for processing large files without loading them entirely into memory. 이는 파일을 메모리에 전체 로드하지 않고 큰 파일을 처리하는 데 유용합니다.

Example 예제:

err := fileutil.ReadChunk("large-file.txt", 1024*1024, func(chunk []byte) error { Process chunk 청크 처리

    fmt.Printf("Read %d bytes\n", len(chunk))
    return nil
})

func ReadFile

func ReadFile(path string) ([]byte, error)

ReadFile reads the entire file and returns its contents as a byte slice ReadFile은 전체 파일을 읽고 내용을 바이트 슬라이스로 반환합니다

Example 예제:

data, err := fileutil.ReadFile("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(data))

func ReadJSON

func ReadJSON(path string, v interface{}) error

ReadJSON reads a JSON file and unmarshals it into the provided value ReadJSON은 JSON 파일을 읽고 제공된 값으로 언마샬합니다

Example 예제:

var config Config
err := fileutil.ReadJSON("config.json", &config)
if err != nil {
    log.Fatal(err)
}

func ReadLines

func ReadLines(path string) ([]string, error)

ReadLines reads a file and returns its contents as a slice of lines ReadLines는 파일을 읽고 내용을 줄의 슬라이스로 반환합니다

Example 예제:

lines, err := fileutil.ReadLines("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
for _, line := range lines {
    fmt.Println(line)
}

func ReadString

func ReadString(path string) (string, error)

ReadString reads the entire file and returns its contents as a string ReadString은 전체 파일을 읽고 내용을 문자열로 반환합니다

Example 예제:

content, err := fileutil.ReadString("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Println(content)

func ReadYAML

func ReadYAML(path string, v interface{}) error

ReadYAML reads a YAML file and unmarshals it into the provided value ReadYAML은 YAML 파일을 읽고 제공된 값으로 언마샬합니다

Example 예제:

var config Config
err := fileutil.ReadYAML("config.yaml", &config)
if err != nil {
    log.Fatal(err)
}

func Rel

func Rel(basepath, targpath string) (string, error)

Rel returns the relative path from basepath to targpath Rel은 basepath에서 targpath로의 상대 경로를 반환합니다

Example 예제:

relPath, err := fileutil.Rel("/base/path", "/base/path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Println(relPath) // "to/file.txt"

func RemoveEmpty

func RemoveEmpty(path string) error

RemoveEmpty removes all empty directories recursively under the given path RemoveEmpty는 주어진 경로 아래의 모든 빈 디렉토리를 재귀적으로 제거합니다

Example 예제:

err := fileutil.RemoveEmpty("path/to/directory")
if err != nil {
    log.Fatal(err)
}

func Rename

func Rename(old, new string) error

Rename renames a file or directory Rename은 파일 또는 디렉토리의 이름을 변경합니다

This is an alias for os.Rename. 이는 os.Rename의 별칭입니다.

Example 예제:

err := fileutil.Rename("old-name.txt", "new-name.txt")
if err != nil {
    log.Fatal(err)
}

func RenameExt

func RenameExt(path, newExt string) error

RenameExt renames a file by changing its extension RenameExt는 파일의 확장자를 변경하여 이름을 변경합니다

Example 예제:

err := fileutil.RenameExt("file.txt", ".md")
if err != nil {
    log.Fatal(err)
}
// Result: "file.md"

func SHA1

func SHA1(path string) (string, error)

SHA1 calculates the SHA1 hash of a file SHA1은 파일의 SHA1 해시를 계산합니다

Example 예제:

hash, err := fileutil.SHA1("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Println("SHA1:", hash)

func SHA256

func SHA256(path string) (string, error)

SHA256 calculates the SHA256 hash of a file SHA256은 파일의 SHA256 해시를 계산합니다

Example 예제:

hash, err := fileutil.SHA256("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Println("SHA256:", hash)

func SHA512

func SHA512(path string) (string, error)

SHA512 calculates the SHA512 hash of a file SHA512는 파일의 SHA512 해시를 계산합니다

Example 예제:

hash, err := fileutil.SHA512("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Println("SHA512:", hash)

func SafeMove

func SafeMove(src, dst string) error

SafeMove moves a file or directory safely by copying first and then deleting SafeMove는 먼저 복사한 다음 삭제하여 파일 또는 디렉토리를 안전하게 이동합니다

This is slower than MoveFile/MoveDir but ensures data integrity. 이는 MoveFile/MoveDir보다 느리지만 데이터 무결성을 보장합니다.

Example 예제:

err := fileutil.SafeMove("source.txt", "destination.txt")
if err != nil {
    log.Fatal(err)
}

func Size

func Size(path string) (int64, error)

Size returns the size of a file in bytes Size는 파일의 크기를 바이트로 반환합니다

Example 예제:

size, err := fileutil.Size("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("File size: %d bytes\n", size)

func SizeHuman

func SizeHuman(path string) (string, error)

SizeHuman returns the file size in a human-readable format (e.g., "1.5 MB") SizeHuman은 사람이 읽기 쉬운 형식으로 파일 크기를 반환합니다 (예: "1.5 MB")

Example 예제:

size, err := fileutil.SizeHuman("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("File size: %s\n", size)

func Split

func Split(path string) (dir, file string)

Split splits a path into directory and file components Split은 경로를 디렉토리와 파일 구성 요소로 분할합니다

This is an alias for filepath.Split. 이는 filepath.Split의 별칭입니다.

Example 예제:

dir, file := fileutil.Split("path/to/file.txt")
// dir = "path/to/", file = "file.txt"

func Stat

func Stat(path string) (os.FileInfo, error)

Stat returns the FileInfo for a file or directory Stat은 파일 또는 디렉토리의 FileInfo를 반환합니다

Example 예제:

info, err := fileutil.Stat("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Name: %s, Size: %d\n", info.Name(), info.Size())

func SyncDirs

func SyncDirs(src, dst string) error

SyncDirs synchronizes the contents of two directories SyncDirs는 두 디렉토리의 내용을 동기화합니다

This function copies new and updated files from src to dst. Files in dst that don't exist in src are not removed. 이 함수는 src에서 dst로 새 파일과 업데이트된 파일을 복사합니다. src에 존재하지 않는 dst의 파일은 제거되지 않습니다.

Example 예제:

err := fileutil.SyncDirs("source-dir", "destination-dir")
if err != nil {
    log.Fatal(err)
}

func ToSlash

func ToSlash(path string) string

ToSlash converts a path to use forward slashes ToSlash는 경로를 슬래시로 변환합니다

This is an alias for filepath.ToSlash. 이는 filepath.ToSlash의 별칭입니다.

Example 예제:

slashPath := fileutil.ToSlash("path\\to\\file.txt")
// Result: "path/to/file.txt"

func Touch

func Touch(path string) error

Touch creates a file if it doesn't exist, or updates its modification time if it does Touch는 파일이 존재하지 않으면 생성하고, 존재하면 수정 시간을 업데이트합니다

Example 예제:

err := fileutil.Touch("path/to/file.txt")
if err != nil {
    log.Fatal(err)
}

func VerifyChecksum

func VerifyChecksum(path, expectedChecksum string) (bool, error)

VerifyChecksum verifies that a file's checksum matches the expected value VerifyChecksum은 파일의 체크섬이 예상 값과 일치하는지 확인합니다

Example 예제:

expected := "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
valid, err := fileutil.VerifyChecksum("path/to/file.txt", expected)
if err != nil {
    log.Fatal(err)
}
if !valid {
    fmt.Println("Checksum mismatch!")
}

func Walk

func Walk(root string, fn filepath.WalkFunc) error

Walk walks the file tree rooted at root, calling fn for each file or directory Walk는 root를 루트로 하는 파일 트리를 순회하며 각 파일 또는 디렉토리에 대해 fn을 호출합니다

This is an alias for filepath.Walk. 이는 filepath.Walk의 별칭입니다.

Example 예제:

err := fileutil.Walk(".", func(path string, info os.FileInfo, err error) error {
    if err != nil {
        return err
    }
    fmt.Println(path)
    return nil
})

func WalkDirs

func WalkDirs(root string, fn func(path string, info os.FileInfo) error) error

WalkDirs walks the file tree and calls fn only for directories WalkDirs는 파일 트리를 순회하며 디렉토리에 대해서만 fn을 호출합니다

Example 예제:

err := fileutil.WalkDirs(".", func(path string, info os.FileInfo) error {
    fmt.Println("Directory:", path)
    return nil
})

func WalkFiles

func WalkFiles(root string, fn func(path string, info os.FileInfo) error) error

WalkFiles walks the file tree and calls fn only for files WalkFiles는 파일 트리를 순회하며 파일에 대해서만 fn을 호출합니다

Example 예제:

err := fileutil.WalkFiles(".", func(path string, info os.FileInfo) error {
    fmt.Println("File:", path)
    return nil
})

func WithoutExt

func WithoutExt(path string) string

WithoutExt returns the path without the file extension WithoutExt는 파일 확장자를 제외한 경로를 반환합니다

Example 예제:

path := fileutil.WithoutExt("file.txt")
// Result: "file"

func WriteAtomic

func WriteAtomic(path string, data []byte, perm ...os.FileMode) error

WriteAtomic writes data to a file atomically by writing to a temporary file first and then renaming it to the target path WriteAtomic는 먼저 임시 파일에 쓴 다음 대상 경로로 이름을 변경하여 파일에 원자적으로 데이터를 씁니다

This prevents corruption if the write operation is interrupted. 이는 쓰기 작업이 중단될 경우 손상을 방지합니다.

Example 예제:

err := fileutil.WriteAtomic("important.txt", []byte("Critical data"))
if err != nil {
    log.Fatal(err)
}

func WriteCSV

func WriteCSV(path string, records [][]string, perm ...os.FileMode) error

WriteCSV writes records to a CSV file WriteCSV는 레코드를 CSV 파일에 씁니다

Example 예제:

records := [][]string{
    {"Name", "Age", "City"},
    {"Alice", "30", "Seoul"},
    {"Bob", "25", "Busan"},
}
err := fileutil.WriteCSV("data.csv", records)
if err != nil {
    log.Fatal(err)
}

func WriteFile

func WriteFile(path string, data []byte, perm ...os.FileMode) error

WriteFile writes data to a file, creating the directory if it doesn't exist WriteFile은 파일에 데이터를 쓰고, 디렉토리가 존재하지 않으면 생성합니다

Example 예제:

err := fileutil.WriteFile("path/to/file.txt", []byte("Hello, World!"))
if err != nil {
    log.Fatal(err)
}

func WriteJSON

func WriteJSON(path string, v interface{}, perm ...os.FileMode) error

WriteJSON marshals a value to JSON and writes it to a file WriteJSON은 값을 JSON으로 마샬하고 파일에 씁니다

Example 예제:

config := Config{Name: "app", Version: "1.0.0"}
err := fileutil.WriteJSON("config.json", config)
if err != nil {
    log.Fatal(err)
}

func WriteLines

func WriteLines(path string, lines []string, perm ...os.FileMode) error

WriteLines writes a slice of lines to a file, creating the directory if it doesn't exist WriteLines는 줄의 슬라이스를 파일에 쓰고, 디렉토리가 존재하지 않으면 생성합니다

Example 예제:

lines := []string{"Line 1", "Line 2", "Line 3"}
err := fileutil.WriteLines("path/to/file.txt", lines)
if err != nil {
    log.Fatal(err)
}

func WriteString

func WriteString(path string, content string, perm ...os.FileMode) error

WriteString writes a string to a file, creating the directory if it doesn't exist WriteString은 파일에 문자열을 쓰고, 디렉토리가 존재하지 않으면 생성합니다

Example 예제:

err := fileutil.WriteString("path/to/file.txt", "Hello, World!")
if err != nil {
    log.Fatal(err)
}

func WriteYAML

func WriteYAML(path string, v interface{}, perm ...os.FileMode) error

WriteYAML marshals a value to YAML and writes it to a file WriteYAML은 값을 YAML로 마샬하고 파일에 씁니다

Example 예제:

config := Config{Name: "app", Version: "1.0.0"}
err := fileutil.WriteYAML("config.yaml", config)
if err != nil {
    log.Fatal(err)
}

Types

type CopyOption

type CopyOption func(*copyOptions)

CopyOption is a functional option for file copy operations CopyOption은 파일 복사 작업을 위한 함수형 옵션입니다

func WithFilter

func WithFilter(fn func(path string, info os.FileInfo) bool) CopyOption

WithFilter sets a filter function to include/exclude files during copy WithFilter는 복사 중 파일을 포함/제외하는 필터 함수를 설정합니다

Example 예제:

err := fileutil.CopyDir(src, dst, fileutil.WithFilter(func(path string, info os.FileInfo) bool {
    return !strings.HasPrefix(info.Name(), ".")
}))

func WithOverwrite

func WithOverwrite(overwrite bool) CopyOption

WithOverwrite sets whether to overwrite existing files WithOverwrite는 기존 파일을 덮어쓸지 여부를 설정합니다

Example 예제:

err := fileutil.CopyFile(src, dst, fileutil.WithOverwrite(true))

func WithPreservePermissions

func WithPreservePermissions(preserve bool) CopyOption

WithPreservePermissions sets whether to preserve file permissions WithPreservePermissions는 파일 권한을 보존할지 여부를 설정합니다

Example 예제:

err := fileutil.CopyFile(src, dst, fileutil.WithPreservePermissions(true))

func WithPreserveTimestamps

func WithPreserveTimestamps(preserve bool) CopyOption

WithPreserveTimestamps sets whether to preserve file timestamps WithPreserveTimestamps는 파일 타임스탬프를 보존할지 여부를 설정합니다

Example 예제:

err := fileutil.CopyFile(src, dst, fileutil.WithPreserveTimestamps(true))

func WithProgress

func WithProgress(fn func(written, total int64)) CopyOption

WithProgress sets a progress callback function WithProgress는 진행 상황 콜백 함수를 설정합니다

Example 예제:

err := fileutil.CopyFile(src, dst, fileutil.WithProgress(func(written, total int64) {
    fmt.Printf("Progress: %d/%d bytes\n", written, total)
}))

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL