File 클래스

File 클래스 (File)

File 객체는 기반 플랫폼의 파일을 나타내는 표현이에요. File 클래스는 FileTest 모듈을 확장해서 File.exist? 같은 싱글턴 메서드들을 지원해요. FileIO 클래스를 상속받아요.

출처: Ruby 3.3 API

본문

많은 예시에서 쓰이는 변수들이에요.

# English text with newlines.
text =  "тест"

# Binary data.
data = "\u9990\u9991\u9992\u9993\u9994"

# Text file.
File.write('t.txt', text)

# File with Russian text.
File.write('t.rus', russian)

# File with binary data.
f = File.new('t.dat', 'wb:UTF-16')
f.write(data)
f.close

접근 모드 (Access Modes)

File.newFile.open은 각각 주어진 파일 경로에 대해 File 객체를 만들어요. 문자열 mode 인자는 1~2문자의 읽기/쓰기 모드로 시작하고, 1문자 데이터 모드와 1문자 파일-생성 모드를 포함할 수 있어요.

기존 파일의 읽기/쓰기 모드 요약표

|------|-----------|----------|----------|----------|-----------|
| R/W  | Initial   |          | Initial  |          | Initial   |
| Mode | Truncate? |  Read    | Read Pos |  Write   | Write Pos |
|------|-----------|----------|----------|----------|-----------|
| 'r'  |    No     | Anywhere |    0     |   Error  |     -     |
| 'w'  |    Yes    |   Error  |    -     | Anywhere |     0     |
| 'a'  |    No     |   Error  |    -     | End only |    End    |
| 'r+' |    No     | Anywhere |    0     | Anywhere |     0     |
| 'w+' |    Yes    | Anywhere |    0     | Anywhere |     0     |
| 'a+' |    No     | Anywhere |   End    | End only |    End    |
|------|-----------|----------|----------|----------|-----------|

생성할 파일의 읽기/쓰기 모드 요약표

|------|----------|----------|----------|-----------|
| R/W  |          | Initial  |          | Initial   |
| Mode |  Read    | Read Pos |  Write   | Write Pos |
|------|----------|----------|----------|-----------|
| 'w'  |   Error  |    -     | Anywhere |     0     |
| 'a'  |   Error  |    -     | End only |     0     |
| 'w+' | Anywhere |    0     | Anywhere |     0     |
| 'a+' | Anywhere |    0     | End only |    End    |
|------|----------|----------|----------|-----------|
  • 'r', 'r+' 모드는 존재하지 않는 파일에선 허용되지 않아요(예외 발생).
  • Anywhere: IO#rewind, IO#pos=, IO#seek로 파일 위치를 바꿔 어디서든 읽기·쓰기가 가능해요.
  • End only: 파일 끝에서만 쓰기가 가능하고, IO#rewind·IO#pos=·IO#seek는 쓰기에 영향을 주지 않아요.
  • Error: 허용되지 않는 읽기·쓰기를 시도하면 예외가 발생해요.

데이터 모드 (Data Mode): 데이터를 텍스트로 볼지 이진 데이터로 볼지 지정하려면 위의 문자열 읽기/쓰기 모드에 다음을 붙여요.

  • 't': 텍스트 데이터. 기본 외부 인코딩을 Encoding::UTF_8로 설정. Windows에서는 EOL/CRLF 변환과 0x1A의 EOF 마커 해석을 활성화.
  • 'b': 이진 데이터. 기본 외부 인코딩을 Encoding::ASCII_8BIT로 설정. Windows에서는 위 변환·해석을 억제.

둘 다 안 주면 기본은 텍스트 데이터예요. 데이터 모드를 지정하면 읽기/쓰기 모드는 생략할 수 없고, 데이터 모드가 파일-생성 모드보다 먼저 와야 해요.

File.new('t.txt', 'rt')
File.new('t.dat', 'rb')

File.new('t.dat', 'b')   # Raises an exception.
File.new('t.dat', 'rxb') # Raises an exception.

파일-생성 모드 (File-Create Mode): 쓰기 가능한 문자열 모드에 다음을 붙여요. 'x': 파일이 없으면 만들고, 있으면 예외를 발생시켜요.

File.new('t.tmp', 'wx')

정수 접근 모드 (Integer Access Modes): mode가 정수면 |(비트 OR)로 결합할 수 있는 다음 상수 중 하나 이상이어야 해요.

  • File::RDONLY — 읽기 전용
  • File::WRONLY — 쓰기 전용
  • File::RDWR — 읽기/쓰기
  • File::APPEND — append 전용
  • File::CREAT — 파일이 없으면 생성
  • File::EXCLFile::CREAT와 함께 주고 파일이 있으면 예외
File.new('t.txt', File::RDONLY)
File.new('t.tmp', File::RDWR | File::CREAT | File::EXCL)

데이터 모드는 정수로 지정할 수 없어요. 정수 모드에서는 항상 텍스트 데이터예요. File::BINARY 상수를 정수 모드에 넣어도 효과가 없어요(줄 코드 변환만 끄고 외부 인코딩은 바꾸지 않기 때문).

인코딩 (Encodings): 문자열 모드에 인코딩 이름(외부만, 또는 외부·내부 둘 다, 콜론으로 구분)을 붙여 지정할 수 있어요.

f = File.new('t.dat', 'rb')
f.external_encoding # => #<Encoding:ASCII-8BIT>
f.internal_encoding # => nil
f = File.new('t.dat', 'rb:UTF-16')
f.external_encoding # => #<Encoding:UTF-16>
f.internal_encoding # => nil
f = File.new('t.dat', 'rb:UTF-16:UTF-16')
f.external_encoding # => #<Encoding:UTF-16>
f.internal_encoding # => #<Encoding:UTF-16>
f.close

외부 인코딩을 설정하면 읽는 문자열은 그 인코딩으로 태그되고, 쓰는 문자열은 그 인코딩으로 변환돼요. 둘 다 설정하면 읽기는 외부→내부, 쓰기는 내부→외부로 변환돼요. 외부 인코딩이 'BOM|UTF-8', 'BOM|UTF-16LE', 'BOM|UTF16-BE'면 입력 문서의 BOM을 검사해 인코딩을 결정해요(찾으면 제거하고 그 인코딩 사용). BOM 옵션은 대소문자에 무관해요.

파일 권한 (File Permissions): File 객체에는 권한(permissions)이 있어요. mode 메서드(이름과 달리)가 권한을 돌려줘요.

f = File.new('t.txt')
f.lstat.mode.to_s(8) # => "100644"

Unix 기반 OS에서 낮은 세 자리 8진수는 owner(6)·group(4)·world(4)의 권한이고, 각 8진수의 비트 3개는 각각 읽기·쓰기·실행을 나타내요. 디렉토리에서 실행 비트는 "탐색 가능"을 뜻해요. 실제 파일을 만드는 메서드에는 권한을 지정할 수 있어요.

File.new('t.tmp', File::CREAT, 0644)
File.new('t.tmp', File::CREAT, 0444)

f = File.new('t.tmp', File::CREAT, 0444)
f.chmod(0644)
f.chmod(0444)

File 상수 (File Constants)

File·IO 메서드에 쓸 여러 상수는 File::Constants 모듈에서 찾을 수 있고, 이름 배열은 File::Constants.constants로 얻을 수 있어요. 별도 상수로는 File::SEPARATOR(경로에서 디렉토리 부분을 구분), File::ALT_SEPARATOR(플랫폼별 대체 구분자), File::PATH_SEPARATOR(경로 목록 구분자)가 있어요.

"What's Here" (메서드 요약)

FileIO에서 파일 생성·읽기·쓰기 메서드를 상속받고, FileTest를 include해 수십 개의 추가 메서드를 제공해요. 여기서 직접 제공하는 메서드들:

  • Creating: ::new, ::open, ::link, ::mkfifo, ::symlink
  • Querying — Paths: ::absolute_path, ::absolute_path?, ::basename, ::dirname, ::expand_path, ::extname, ::fnmatch?(별칭 ::fnmatch), ::join, ::path, ::readlink, ::realdirpath, ::realpath, ::split, path(별칭 to_path)
  • Querying — Times: ::atime, ::birthtime, ::ctime, ::mtime, atime, birthtime, ctime, mtime
  • Querying — Types: ::blockdev?, ::chardev?, ::directory?, ::executable?, ::executable_real?, ::exist?, ::file?, ::ftype, ::grpowned?, ::identical?, ::lstat, ::owned?, ::pipe?, ::readable?, ::readable_real?, ::setgid?, ::setuid?, ::socket?, ::stat, ::sticky?, ::symlink?, ::umask, ::world_readable?, ::world_writable?, ::writable?, ::writable_real?, lstat
  • Querying — Contents: ::empty?(별칭 ::zero?), ::size, ::size?, size
  • Settings: ::chmod, ::chown, ::lchmod, ::lchown, ::lutime, ::rename, ::utime, flock
  • Other: ::truncate, ::unlink(별칭 ::delete), truncate

Public Class Methods

  • absolute_path(file_name [, dir_string] ) → abs_file_name — 경로명을 절대 경로명으로 변환. 상대 경로는 프로세스의 현재 작업 디렉토리 기준(dir_string을 주면 그 시작점으로). ~로 시작하면 확장하지 않고 보통 디렉토리 이름으로 취급해요. File.absolute_path("~oracle/bin") #=> "/~oracle/bin"
  • absolute_path?(file_name) → true/false — file_name이 절대 경로면 true. File.absolute_path?("c:/foo") #=> false (Linux), true (Windows)
  • atime(file_name) → time — 이름이 지정된 파일의 마지막 접근 시간을 Time으로.
  • basename(file_name [, suffix]) → base_name — 파일명의 마지막 구성요소를 반환(뒤의 구분자를 먼저 제거). suffix가 있으면 끝에서 제거하고, ".*"이면 확장자를 제거. File.basename("/home/gumby/work/ruby.rb") #=> "ruby.rb"
  • birthtime(file_name) → time — 파일의 생성 시간. 플랫폼이 지원 안 하면 NotImplementedError.
  • blockdev?(filepath) → true/false — 블록 디바이스인지.
  • chardev?(filepath) → true/false — 문자 디바이스인지.
  • chmod(mode_int, file_name, ...) → integer — 파일 권한 비트를 mode_int로 변경. 처리된 파일 수 반환.
  • chown(owner_int, group_int, file_name, ...) → integer — 소유자·그룹 변경. nil 또는 -1은 무시.
  • ctime(file_name) → time — 파일 메타데이터 변경 시간(File::Stat 참조).
  • delete(file_name, ...) / unlink(file_name, ...) → integer — 파일 삭제. 인자로 준 이름 수 반환. 오류 시 예외(Errno::ENOENT 등).
  • directory?(path) → true/false — 디렉토리(또는 디렉토리로 가는 심볼릭 링크)인지.
  • dirname(file_name, level = 1) → dir_name — 파일 경로의 마지막 구성요소를 뺀 나머지. level을 주면 그 수만큼 뺌. File.dirname("/home/gumby/work/ruby.rb") #=> "/home/gumby/work", File.dirname("/home/gumby/work/ruby.rb", 2) #=> "/home/gumby"
  • empty?(file_name) / zero?(file_name) → true/false — 파일이 존재하고 비어 있는지.
  • executable?, executable_real? → true/false — 유효(실제) 사용자·그룹이 실행 가능한지(FileTest 참고).
  • exist?(file_name) → true/false — 파일이 존재하는지.
  • expand_path(file_name [, dir_string]) → abs_file_name — 절대 경로를 반환하되 ~를 홈 디렉토리로 확장. File.expand_path("~oracle/bin") #=> "/home/oracle/bin", File.expand_path("ruby", "/usr/bin") #=> "/usr/bin/ruby"
  • extname(path) → string — 파일 경로의 확장자.
  • file?(file) → true/false — 일반 파일인지.
  • fnmatch(pattern, path, [flags]) → true/false — 파일 경로가 패턴과 일치하는지. File.fnmatch('cat', 'cat') #=> true, File.fnmatch('c{at,ub}s', 'cats', File::FNM_EXTGLOB) #=> true, File.fnmatch('c?t', 'cat') #=> true
  • ftype(file_name) → string — 파일 타입 문자열. File.ftype("testfile") #=> "file", File.ftype("/dev/tty") #=> "characterSpecial", File.ftype("/tmp/.X11-unix/X0") #=> "socket"
  • grpowned?, identical?, owned?, pipe?, readable?, readable_real?, setgid?, setuid?, socket?, sticky?, symlink?, world_readable?, world_writable?, writable?, writable_real? — FileTest의 파일 테스트 메서드들(부모 FileTest 페이지 참고).
  • join(string, ...) → string — 경로 구성요소를 단일 경로 문자열로 결합. File.join("usr", "mail", "gumby") #=> "usr/mail/gumby"
  • lchmod(mode_int, file_name, ...) → integer — 심볼릭 링크를 따라가지 않고 권한 변경(File::chmod과 동등하되 링크 자체를 변경).
  • lchown(owner_int, group_int, file_name, ...) → integer — 링크를 따라가지 않고 소유권 변경.
  • link(old_name, new_name) → 0 — 하드 링크 생성.
  • lstat(filepath) → stat — 경로의 마지막 심볼릭 링크에 대한 File::Stat 객체.
  • lutime(atime, mtime, file_name, ...) → integer — 마지막 심볼릭 링크의 접근·수정 시간 설정.
  • mkfifo(file_name, mode=0666) → 0 — FIFO(명명된 파이프) 생성.
  • mtime(file_name) → time — 마지막 데이터 수정 시간.
  • new(path, mode = 'r', perm = 0666, **opts) → file — 경로의 파일을 열고 객체 반환.
  • open(path, mode = 'r', perm = 0666, **opts) → file — ::new와 같지만, 블록을 주면 파일을 블록에 넘기고 블록 종료 시 닫음.
  • path(path) → string — 주어진 경로의 문자열 표현.
  • readlink(link_name) → file_name — 심볼릭 링크가 가리키는 경로. File.readlink("link2test") #=> "testfile"
  • realdirpath(pathname [, dir_string]) → real_pathname — 실제 파일시스템의 절대 경로. 마지막 구성요소는 존재하지 않아도 됨. 심볼릭 링크·불필요한 점 없음.
  • realpath(pathname [, dir_string]) → real_pathname — 실제 절대 경로. 모든 구성요소가 존재해야 함.
  • rename(old_name, new_name) → 0 — 파일 이동/이름 변경.
  • size(file_name) → integer — 크기(바이트).
  • size?(file_name) → Integer 또는 nil — 없는 파일이나 빈 파일이면 nil, 아니면 크기.
  • split(file_name) → array — 디렉토리 이름과 basename 두 문자열 배열.
  • stat(filepath) → stat — File::Stat 객체.
  • symlink(old_name, new_name) → 0 — 심볼릭 링크 생성.
  • truncate(file_name, integer) → 0 — 파일을 주어진 크기로 잘라냄.
  • umask() → integer — 현재 프로세스의 umask 값.
  • utime(atime, mtime, file_name, ...) → integer — 각 파일의 접근·수정 시간 설정.
  • world_readable?, world_writable? — 다른 사용자가 읽기/쓰기 가능하면 권한 비트 정수, 아니면 nil.

Public Instance Methods

  • atime → time — 마지막 접근 시간.
  • birthtime → time — 생성 시간.
  • chmod(mode_int) → 0 — 권한 비트 변경.
  • chown(owner_int, group_int) → 0 — 소유·그룹 변경.
  • ctime → time — 메타데이터 변경 시간. Windows(NTFS)에서는 생성 시간 반환.
  • flock(locking_constant) → 0 또는 false — self를 잠그거나 잠금 해제.
  • lstat → stat — 마지막 심볼릭 링크의 File::Stat.
  • mtime → time — 마지막 데이터 수정 시간.
  • size → integer — 크기(바이트).
  • truncate(integer) → 0 — self를 주어진 크기로 잘라냄.