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 str.size unless str.size > 0
128 # reset real pos ignore buf
149 alias_method :eof, :eof?
152 raise IOError if closed?
153 sysseek(0, SEEK_CUR) - @buf.length
155 alias_method :tell, :pos
165 def seek(i, whence = SEEK_SET)
166 raise IOError if closed?
173 return @buf if @buf && @buf.size > 0
174 @buf = sysread(BUF_SIZE)
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.size) ? length : @buf.size
211 array.push @buf[0, consume]
212 @buf = @buf[consume, @buf.size - consume]
225 outbuf.replace(array.join)
229 def readline(arg = $/, limit = nil)
253 array = nil if array.empty?
257 if limit && limit <= @buf.size
258 array.push @buf[0, limit]
259 @buf = @buf[limit, @buf.size - limit]
261 elsif idx = @buf.index(rs)
263 array.push @buf[0, len]
264 @buf = @buf[len, @buf.size - len]
272 raise EOFError.new "end of file reached" if array.nil?
288 @buf = @buf[1, @buf.size]
302 while line = self.gets
309 def each_byte(&block)
310 while char = self.getc
319 alias each_char each_byte
335 write "\n" if (s[-1] != "\n")
338 write "\n" if len == 0
356 alias_method :to_i, :fileno
357 alias_method :tty?, :isatty
360 STDIN = IO.open(0, "r")
361 STDOUT = IO.open(1, "w")
362 STDERR = IO.open(2, "w")
378 $stdout.printf(*args)