4 class IOError < StandardError; end
5 class EOFError < IOError; end
14 def self.open(*args, &block)
17 return io unless block
23 io.close unless io.closed?
29 def self.popen(command, mode = 'r', opts={}, &block)
30 if !self.respond_to?(:_popen)
31 raise NotImplementedError, "popen is not supported on this platform"
33 io = self._popen(command, mode, opts)
34 return io unless block
40 io.close unless io.closed?
48 if !self.respond_to?(:_pipe)
49 raise NotImplementedError, "pipe is not supported on this platform"
56 r.close unless r.closed?
57 w.close unless w.closed?
64 def self.read(path, length=nil, offset=nil, opt=nil)
65 if not opt.nil? # 4 arguments
67 elsif not offset.nil? # 3 arguments
74 elsif not length.nil? # 2 arguments
83 else # only 1 argument
94 io = IO.popen(path[1..-1], (opt[:mode] || "r"))
96 mode = opt[:mode] || "r"
97 fd = IO.sysopen(path, mode)
98 io = IO.open(fd, mode)
100 io.seek(offset) if offset > 0
101 str = io.read(length)
113 # mruby-io always writes immediately (no output buffer).
114 raise IOError, "closed stream" if self.closed?
119 # We must define IO#hash here because IO includes Enumerable and
120 # Enumerable#hash will call IO#read...
125 str = string.is_a?(String) ? string : string.to_s
126 return 0 if str.empty?
128 # reset real pos ignore buf
149 alias_method :eof, :eof?
152 raise IOError if closed?
153 sysseek(0, SEEK_CUR) - @buf.bytesize
155 alias_method :tell, :pos
165 def seek(i, whence = SEEK_SET)
166 raise IOError if closed?
173 return @buf if @buf && @buf.bytesize > 0
174 sysread(BUF_SIZE, @buf)
178 raise TypeError.new "expect String, got #{substr.class}" unless substr.is_a?(String)
187 def read(length = nil, outbuf = "")
189 unless length.is_a? Fixnum
190 raise TypeError.new "can't convert #{length.class} into Integer"
193 raise ArgumentError.new "negative length: #{length} given"
196 return "" # easy case
205 array = nil if array.empty? and (not length.nil?) and length != 0
210 consume = (length <= @buf.bytesize) ? length : @buf.bytesize
211 array.push IO._bufread(@buf, consume)
224 outbuf.replace(array.join)
228 def readline(arg = "\n", limit = nil)
252 array = nil if array.empty?
256 if limit && limit <= @buf.size
257 array.push @buf[0, limit]
260 elsif idx = @buf.index(rs)
262 array.push @buf[0, len]
271 raise EOFError.new "end of file reached" if array.nil?
301 return to_enum unless block
303 while line = self.gets
310 def each_byte(&block)
311 return to_enum(:each_byte) unless block
313 while char = self.getc
322 alias each_char each_byte
338 write "\n" if (s[-1] != "\n")
341 write "\n" if len == 0
359 alias_method :to_i, :fileno
360 alias_method :tty?, :isatty
363 STDIN = IO.open(0, "r")
364 STDOUT = IO.open(1, "w")
365 STDERR = IO.open(2, "w")