IO

IO

IO는 입력·출력 스트림의 기본 클래스예요. 표준 입출력(STDIN, STDOUT, STDERR), 파일, 파이프, 소켓이 모두 IO를 통해 다뤄져요. FileIO의 하위 클래스예요.

출처: Ruby 4.0 API

본문

IO는 바이트·문자·줄 단위로 읽고 쓰는 저수준 인터페이스와, 블록·버퍼링·비블로킹·콘솔 터미널 제어 같은 고수준 기능을 함께 제공해요. 아래에서 클래스 메서드와 인스턴스 메서드를 카테고리별로 정리할게요.

클래스 메서드

디스크립터·스트림 생성

new(fd, mode = 'r', **opts) → io
for_fd(fd, mode = 'r', **opts) → io
open(fd, mode = 'r', **opts) → io
open(fd, mode = 'r', **opts) {|io| ... } → object

파일 디스크립터 fd로 IO 객체를 만들어요. 블록을 주면 io를 넘겨 블록을 실행하고 블록 값을 돌려줘요 (닫기는 자동). **opts로 인코딩 등을 지정할 수 있어요.

pipe(**opts) → [read_io, write_io]
pipe(enc, **opts) → [read_io, write_io]
pipe(ext_enc, int_enc, **opts) → [read_io, write_io]
pipe(**opts) {|read_io, write_io| ... } → object

읽기·쓰기 끝을 연결한 파이프 쌍을 만들어요.

popen(env = {}, cmd, mode = 'r', **opts) → io
popen(env = {}, cmd, mode = 'r', **opts) {|io| ... } → object

서브프로세스를 실행해 그 표준 입출력을 연결한 IO를 돌려줘요.

sysopen(path, mode = 'r', perm = 0666) → integer

경로를 저수준으로 열고 파일 디스크립터(정수)를 돌려줘요.

try_convert(object) → new_io or nil

object를 IO로 변환하려 시도해요. :to_io에 반응하면 변환 결과, 아니면 nil.

select(read_ios, write_ios = [], error_ios = [], timeout = nil) → array or nil

입출력 준비 상태를 폴링해요. 준비된 IO의 [readable, writable, error] 배열을 돌려주고, 타임아웃이면 nil이에요.

copy_stream(src, dst, src_length = nil, src_offset = 0) → integer

한 스트림에서 다른 스트림으로 데이터를 복사하고 복사한 바이트 수를 돌려줘요.

파일 직접 읽기·쓰기

read(path, length = nil, offset = 0, **opts) → string or nil
binread(path, length = nil, offset = 0) → string or nil
readlines(path, sep = $/, **opts) → array
foreach(path, sep = $/, **opts) {|line| block } → nil
binwrite(path, string, offset = 0) → integer
write(path, data, offset = 0, **opts) → integer

IO.read 등은 경로를 직접 열어 읽고 쓰는 편의 메서드예요. binread/binwrite는 바이너리 모드, readlines는 줄 배열, foreach는 줄 단위 반복이에요.

인스턴스 메서드

쓰기

self << object → self          # 오브젝트를 스트림에 씀
print(*objects) → nil
printf(format_string, *objects) → nil
putc(object) → object
puts(*objects) → nil
write(*objects) → integer      # 쓴 바이트 수
write_nonblock(string) → integer
pwrite(object, offset) → integer  # 오프셋 지정 쓰기
syswrite(object) → integer     # 버퍼링 없는 저수준 쓰기

읽기

getc → character or nil
gets(sep = $/, chomp: false) → string or nil
read(maxlen = nil, out_string = nil) → new_string, out_string, or nil
readbyte → integer
readchar → string
readline(sep = $/, chomp: false) → string
readlines(sep = $/, chomp: false) → array
readpartial(maxlen) → string
sysread(maxlen) → string
pread(maxlen, offset) → string
ungetbyte(integer) → nil      # 바이트 되돌려 넣기
ungetc(integer) → nil
getbyte → integer or nil
eof → true or false

gets는 줄 단위, readline은 줄을 읽되 끝나면 EOFError, readpartial은 일부 데이터, sysread는 버퍼링 없는 저수준 읽기예요.

반복

each_byte {|byte| ... } → self
each_char {|c| ... } → self
each_codepoint {|c| ... } → self
each_line(sep = $/, chomp: false) {|line| ... } → self
each_line(limit, chomp: false) {|line| ... } → self
each_line(sep, limit, chomp: false) {|line| ... } → self

각각 바이트·문자·코드포인트·줄 단위로 블록을 호출해요. 블록 없이 부르면 enumerator를 돌려줘요.

위치 제어 (Positioning)

pos = new_position → new_position    # 위치 설정 (pos 조회도 가능)
seek(offset, whence = IO::SEEK_SET) → 0
sysseek(offset, whence = IO::SEEK_SET) → integer
tell → integer       # 현재 위치 (pos와 동일)
rewind → 0
lineno → integer      # 줄 번호
lineno = integer → integer

whenceIO::SEEK_SET, IO::SEEK_CUR, IO::SEEK_END를 써요.

상태·속성

autoclose = bool → true or false
autoclose? → true or false
binmode → self              # 바이너리 모드
binmode? → true or false
close → nil
close_on_exec = bool → true or false
close_on_exec? → true or false
close_read → nil
close_write → nil
closed? → true or false
external_encoding → encoding or nil
internal_encoding → encoding or nil
fileno → integer
flush → self
fsync → 0
fdatasync → 0
inspect → string
isatty → true or false
path → string or nil
pid → integer or nil
stat → stat                 # File::Stat
sync → true or false        # 버퍼링 여부
sync = boolean → boolean
to_io → self

인코딩·비블로킹·콘솔

set_encoding(ext_enc) → self
set_encoding(ext_enc, int_enc, **enc_opts) → self
set_encoding('ext_enc:int_enc', **enc_opts) → self
set_encoding_by_bom → encoding or nil   # BOM으로 인코딩 판정
nonblock {|io| } → object
nonblock(boolean) {|io| } → object
nonblock = boolean → boolean
nonblock? → boolean
advise(advice, offset = 0, len = 0) → nil   # 운영체제에 액세스 패턴 힌트
fcntl(integer_cmd, argument) → integer
ioctl(integer_cmd, argument) → integer
pathconf(name) → Integer

대기 (Waiting)

wait(events, timeout) → event mask, false or nil
wait_readable → truthy or falsy
wait_readable(timeout) → truthy or falsy
wait_writable → truthy or falsy
wait_writable(timeout) → truthy or falsy
wait_priority → truthy or falsy
wait_priority(timeout) → truthy or falsy

스트림이 읽기/쓰기 가능해질 때까지 기다려요 (IO::READABLE, IO::WRITABLE, IO::PRIORITY 이벤트).

timeout → duration or nil
timeout = duration → duration
timeout = nil → nil

읽기·쓰기 타임아웃을 설정해요. 초과하면 IO::TimeoutError가 나요.

터미널·콘솔 제어

console → #<File:/dev/tty>
console_mode → mode
raw!(min: nil, time: nil, intr: nil) → io   # 콘솔 raw 모드
echo? → true or false
getch(min: nil, time: nil, intr: nil) → char
getpass(prompt=nil) → string                # 입력을 보여주지 않고 읽음
clear_screen → io
cursor → [row, column]
cursor_down(n) → io
cursor_left(n) → io
cursor_right(n) → io
cursor_up(n) → io
erase_line(mode) → io
erase_screen(mode) → io
goto(line, column) → io
goto_column(column) → io
scroll_backward(n) → io
scroll_forward(n) → io
winsize → [rows, columns]
ttyname → string or nil

이들은 콘솔 터미널 관련 기능이에요.

기타

reopen(other_io) → self
reopen(path, mode = 'r', **opts) → self
check_winsize_changed { ... } → io
expect(pattern, timeout = 9999999) → Array
expect(pattern, timeout = 9999999) {|result| ... } → nil
pressed?(key) → bool

reopen은 다른 IO나 경로로 스트림을 다시 열어요. expect는 패턴이 나타날 때까지 기다려요(보통 소켓 통신에서).