* io.c (mode_enc): modify enc and enc2 consistently.
[ruby-svn.git] / io.c
blob18eefb247490890965753abb2973e0d0a2646720
1 /**********************************************************************
3 io.c -
5 $Author$
6 created at: Fri Oct 15 18:08:59 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
12 **********************************************************************/
14 #include "ruby/ruby.h"
15 #include "ruby/io.h"
16 #include "ruby/signal.h"
17 #include "vm_core.h"
18 #include <ctype.h>
19 #include <errno.h>
21 #define free(x) xfree(x)
23 #if defined(DOSISH) || defined(__CYGWIN__)
24 #include <io.h>
25 #endif
27 #include <sys/types.h>
28 #if defined HAVE_NET_SOCKET_H
29 # include <net/socket.h>
30 #elif defined HAVE_SYS_SOCKET_H
31 # include <sys/socket.h>
32 #endif
34 #if defined(MSDOS) || defined(__BOW__) || defined(__CYGWIN__) || defined(_WIN32) || defined(__human68k__) || defined(__EMX__) || defined(__BEOS__)
35 # define NO_SAFE_RENAME
36 #endif
38 #if defined(MSDOS) || defined(__CYGWIN__) || defined(_WIN32)
39 # define NO_LONG_FNAME
40 #endif
42 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(sun) || defined(_nec_ews)
43 # define USE_SETVBUF
44 #endif
46 #ifdef __QNXNTO__
47 #include "unix.h"
48 #endif
50 #include <sys/types.h>
51 #if defined(HAVE_SYS_IOCTL_H) && !defined(DJGPP) && !defined(_WIN32) && !defined(__human68k__)
52 #include <sys/ioctl.h>
53 #endif
54 #if defined(HAVE_FCNTL_H) || defined(_WIN32)
55 #include <fcntl.h>
56 #elif defined(HAVE_SYS_FCNTL_H)
57 #include <sys/fcntl.h>
58 #endif
60 #if !HAVE_OFF_T && !defined(off_t)
61 # define off_t long
62 #endif
64 #include <sys/stat.h>
66 /* EMX has sys/param.h, but.. */
67 #if defined(HAVE_SYS_PARAM_H) && !(defined(__EMX__) || defined(__HIUX_MPP__))
68 # include <sys/param.h>
69 #endif
71 #if !defined NOFILE
72 # define NOFILE 64
73 #endif
75 #ifdef HAVE_UNISTD_H
76 #include <unistd.h>
77 #endif
79 #ifdef HAVE_SYSCALL_H
80 #include <syscall.h>
81 #elif defined HAVE_SYS_SYSCALL_H
82 #include <sys/syscall.h>
83 #endif
85 extern void Init_File(void);
87 #ifdef __BEOS__
88 # ifndef NOFILE
89 # define NOFILE (OPEN_MAX)
90 # endif
91 #endif
93 #include "ruby/util.h"
95 #ifndef O_ACCMODE
96 #define O_ACCMODE (O_RDONLY | O_WRONLY | O_RDWR)
97 #endif
99 #if SIZEOF_OFF_T > SIZEOF_LONG && !defined(HAVE_LONG_LONG)
100 # error off_t is bigger than long, but you have no long long...
101 #endif
103 #ifndef PIPE_BUF
104 # ifdef _POSIX_PIPE_BUF
105 # define PIPE_BUF _POSIX_PIPE_BUF
106 # else
107 # define PIPE_BUF 512 /* is this ok? */
108 # endif
109 #endif
111 VALUE rb_cIO;
112 VALUE rb_eEOFError;
113 VALUE rb_eIOError;
115 VALUE rb_stdin, rb_stdout, rb_stderr;
116 VALUE rb_deferr; /* rescue VIM plugin */
117 static VALUE orig_stdout, orig_stderr;
119 VALUE rb_output_fs;
120 VALUE rb_rs;
121 VALUE rb_output_rs;
122 VALUE rb_default_rs;
124 static VALUE argf;
126 static ID id_write, id_read, id_getc, id_flush, id_encode, id_readpartial;
127 static VALUE sym_mode, sym_perm, sym_extenc, sym_intenc, sym_encoding, sym_open_args;
129 struct timeval rb_time_interval(VALUE);
131 struct argf {
132 VALUE filename, current_file;
133 int gets_lineno;
134 int init_p, next_p;
135 VALUE lineno;
136 VALUE argv;
137 char *inplace;
138 int binmode;
139 rb_encoding *enc, *enc2;
142 static int max_file_descriptor = NOFILE;
143 #define UPDATE_MAXFD(fd) \
144 do { \
145 if (max_file_descriptor < (fd)) max_file_descriptor = (fd); \
146 } while (0)
148 #define argf_of(obj) (*(struct argf *)DATA_PTR(obj))
149 #define ARGF argf_of(argf)
151 #ifdef _STDIO_USES_IOSTREAM /* GNU libc */
152 # ifdef _IO_fpos_t
153 # define STDIO_READ_DATA_PENDING(fp) ((fp)->_IO_read_ptr != (fp)->_IO_read_end)
154 # else
155 # define STDIO_READ_DATA_PENDING(fp) ((fp)->_gptr < (fp)->_egptr)
156 # endif
157 #elif defined(FILE_COUNT)
158 # define STDIO_READ_DATA_PENDING(fp) ((fp)->FILE_COUNT > 0)
159 #elif defined(FILE_READEND)
160 # define STDIO_READ_DATA_PENDING(fp) ((fp)->FILE_READPTR < (fp)->FILE_READEND)
161 #elif defined(__BEOS__)
162 # define STDIO_READ_DATA_PENDING(fp) (fp->_state._eof == 0)
163 #elif defined(__VMS)
164 # define STDIO_READ_DATA_PENDING(fp) (((unsigned int)(*(fp))->_cnt) > 0)
165 #else
166 # define STDIO_READ_DATA_PENDING(fp) (!feof(fp))
167 #endif
169 #if defined(__VMS)
170 #define fopen(file_spec, mode) fopen(file_spec, mode, "rfm=stmlf")
171 #define open(file_spec, flags, mode) open(file_spec, flags, mode, "rfm=stmlf")
172 #endif
174 #define GetWriteIO(io) rb_io_get_write_io(io)
176 #define READ_DATA_PENDING(fptr) ((fptr)->rbuf_len)
177 #define READ_DATA_PENDING_COUNT(fptr) ((fptr)->rbuf_len)
178 #define READ_DATA_PENDING_PTR(fptr) ((fptr)->rbuf+(fptr)->rbuf_off)
179 #define READ_DATA_BUFFERED(fptr) READ_DATA_PENDING(fptr)
181 #define READ_CHECK(fptr) do {\
182 if (!READ_DATA_PENDING(fptr)) {\
183 rb_thread_wait_fd((fptr)->fd);\
184 rb_io_check_closed(fptr);\
186 } while(0)
188 #ifndef S_ISSOCK
189 # ifdef _S_ISSOCK
190 # define S_ISSOCK(m) _S_ISSOCK(m)
191 # else
192 # ifdef _S_IFSOCK
193 # define S_ISSOCK(m) ((m & S_IFMT) == _S_IFSOCK)
194 # else
195 # ifdef S_IFSOCK
196 # define S_ISSOCK(m) ((m & S_IFMT) == S_IFSOCK)
197 # endif
198 # endif
199 # endif
200 #endif
202 #if !defined HAVE_SHUTDOWN && !defined shutdown
203 #define shutdown(a,b) 0
204 #endif
206 #if defined(_WIN32)
207 #define is_socket(fd, path) rb_w32_is_socket(fd)
208 #elif !defined(S_ISSOCK)
209 #define is_socket(fd, path) 0
210 #else
211 static int
212 is_socket(int fd, const char *path)
214 struct stat sbuf;
215 if (fstat(fd, &sbuf) < 0)
216 rb_sys_fail(path);
217 return S_ISSOCK(sbuf.st_mode);
219 #endif
221 void
222 rb_eof_error(void)
224 rb_raise(rb_eEOFError, "end of file reached");
227 VALUE
228 rb_io_taint_check(VALUE io)
230 if (!OBJ_UNTRUSTED(io) && rb_safe_level() >= 4)
231 rb_raise(rb_eSecurityError, "Insecure: operation on trusted IO");
232 rb_check_frozen(io);
233 return io;
236 void
237 rb_io_check_initialized(rb_io_t *fptr)
239 if (!fptr) {
240 rb_raise(rb_eIOError, "uninitialized stream");
244 void
245 rb_io_check_closed(rb_io_t *fptr)
247 rb_io_check_initialized(fptr);
248 if (fptr->fd < 0) {
249 rb_raise(rb_eIOError, "closed stream");
253 static int io_fflush(rb_io_t *);
255 VALUE
256 rb_io_get_io(VALUE io)
258 return rb_convert_type(io, T_FILE, "IO", "to_io");
261 static VALUE
262 rb_io_check_io(VALUE io)
264 return rb_check_convert_type(io, T_FILE, "IO", "to_io");
267 VALUE
268 rb_io_get_write_io(VALUE io)
270 VALUE write_io;
271 rb_io_check_initialized(RFILE(io)->fptr);
272 write_io = RFILE(io)->fptr->tied_io_for_writing;
273 if (write_io) {
274 return write_io;
276 return io;
280 * call-seq:
281 * IO.try_convert(obj) -> io or nil
283 * Try to convert <i>obj</i> into an IO, using to_io method.
284 * Returns converted IO or nil if <i>obj</i> cannot be converted
285 * for any reason.
287 * IO.try_convert(STDOUT) # => STDOUT
288 * IO.try_convert("STDOUT") # => nil
290 static VALUE
291 rb_io_s_try_convert(VALUE dummy, VALUE io)
293 return rb_io_check_io(io);
296 static void
297 io_unread(rb_io_t *fptr)
299 off_t r;
300 rb_io_check_closed(fptr);
301 if (fptr->rbuf_len == 0 || fptr->mode & FMODE_DUPLEX)
302 return;
303 /* xxx: target position may be negative if buffer is filled by ungetc */
304 #if defined(_WIN32) || defined(DJGPP) || defined(__CYGWIN__) || defined(__human68k__) || defined(__EMX__)
305 if (!(fptr->mode & FMODE_BINMODE)) {
306 int len = fptr->rbuf_len;
307 while (fptr->rbuf_len-- > 0) {
308 if (fptr->rbuf[fptr->rbuf_len] == '\n')
309 ++len;
311 r = lseek(fptr->fd, -len, SEEK_CUR);
313 else
314 #endif
315 r = lseek(fptr->fd, -fptr->rbuf_len, SEEK_CUR);
316 if (r < 0) {
317 if (errno == ESPIPE)
318 fptr->mode |= FMODE_DUPLEX;
319 return;
321 fptr->rbuf_off = 0;
322 fptr->rbuf_len = 0;
323 return;
326 static rb_encoding *io_input_encoding(rb_io_t *fptr);
328 static void
329 io_ungetc(VALUE str, rb_io_t *fptr)
331 int len = RSTRING_LEN(str);
333 if (rb_enc_dummy_p(io_input_encoding(fptr))) {
334 rb_raise(rb_eNotImpError, "ungetc against dummy encoding is not currently supported");
337 if (fptr->rbuf == NULL) {
338 fptr->rbuf_off = 0;
339 fptr->rbuf_len = 0;
340 if (len > 8192)
341 fptr->rbuf_capa = len;
342 else
343 fptr->rbuf_capa = 8192;
344 fptr->rbuf = ALLOC_N(char, fptr->rbuf_capa);
346 if (fptr->rbuf_capa < len + fptr->rbuf_len) {
347 rb_raise(rb_eIOError, "ungetc failed");
349 if (fptr->rbuf_off < len) {
350 MEMMOVE(fptr->rbuf+fptr->rbuf_capa-fptr->rbuf_len,
351 fptr->rbuf+fptr->rbuf_off,
352 char, fptr->rbuf_len);
353 fptr->rbuf_off = fptr->rbuf_capa-fptr->rbuf_len;
355 fptr->rbuf_off-=len;
356 fptr->rbuf_len+=len;
357 MEMMOVE(fptr->rbuf+fptr->rbuf_off, RSTRING_PTR(str), char, len);
360 static rb_io_t *
361 flush_before_seek(rb_io_t *fptr)
363 io_fflush(fptr);
364 io_unread(fptr);
365 errno = 0;
366 return fptr;
369 #define io_seek(fptr, ofs, whence) lseek(flush_before_seek(fptr)->fd, ofs, whence)
370 #define io_tell(fptr) lseek(flush_before_seek(fptr)->fd, 0, SEEK_CUR)
372 #ifndef SEEK_CUR
373 # define SEEK_SET 0
374 # define SEEK_CUR 1
375 # define SEEK_END 2
376 #endif
378 #define FMODE_SYNCWRITE (FMODE_SYNC|FMODE_WRITABLE)
380 void
381 rb_io_check_readable(rb_io_t *fptr)
383 rb_io_check_closed(fptr);
384 if (!(fptr->mode & FMODE_READABLE)) {
385 rb_raise(rb_eIOError, "not opened for reading");
387 if (fptr->wbuf_len) {
388 io_fflush(fptr);
390 if (fptr->tied_io_for_writing) {
391 rb_io_t *wfptr;
392 GetOpenFile(fptr->tied_io_for_writing, wfptr);
393 io_fflush(wfptr);
395 if (!fptr->enc && fptr->fd == 0) {
396 fptr->enc = rb_default_external_encoding();
400 static rb_encoding*
401 io_read_encoding(rb_io_t *fptr)
403 if (fptr->enc) {
404 return fptr->enc;
406 return rb_default_external_encoding();
409 static rb_encoding*
410 io_input_encoding(rb_io_t *fptr)
412 if (fptr->enc2) {
413 return fptr->enc2;
415 return io_read_encoding(fptr);
418 void
419 rb_io_check_writable(rb_io_t *fptr)
421 rb_io_check_closed(fptr);
422 if (!(fptr->mode & FMODE_WRITABLE)) {
423 rb_raise(rb_eIOError, "not opened for writing");
425 if (fptr->rbuf_len) {
426 io_unread(fptr);
431 rb_read_pending(FILE *fp)
433 return STDIO_READ_DATA_PENDING(fp);
437 rb_io_read_pending(rb_io_t *fptr)
439 return READ_DATA_PENDING(fptr);
442 void
443 rb_read_check(FILE *fp)
445 if (!STDIO_READ_DATA_PENDING(fp)) {
446 rb_thread_wait_fd(fileno(fp));
450 void
451 rb_io_read_check(rb_io_t *fptr)
453 if (!READ_DATA_PENDING(fptr)) {
454 rb_thread_wait_fd(fptr->fd);
456 return;
459 static int
460 ruby_dup(int orig)
462 int fd;
464 fd = dup(orig);
465 if (fd < 0) {
466 if (errno == EMFILE || errno == ENFILE || errno == ENOMEM) {
467 rb_gc();
468 fd = dup(orig);
470 if (fd < 0) {
471 rb_sys_fail(0);
474 return fd;
477 static VALUE
478 io_alloc(VALUE klass)
480 NEWOBJ(io, struct RFile);
481 OBJSETUP(io, klass, T_FILE);
483 io->fptr = 0;
485 return (VALUE)io;
488 #ifndef S_ISREG
489 # define S_ISREG(m) ((m & S_IFMT) == S_IFREG)
490 #endif
492 static int
493 wsplit_p(rb_io_t *fptr)
495 #if defined(HAVE_FCNTL) && defined(F_GETFL) && defined(O_NONBLOCK)
496 int r;
497 #endif
499 if (!(fptr->mode & FMODE_WSPLIT_INITIALIZED)) {
500 struct stat buf;
501 if (fstat(fptr->fd, &buf) == 0 &&
502 !S_ISREG(buf.st_mode)
503 #if defined(HAVE_FCNTL) && defined(F_GETFL) && defined(O_NONBLOCK)
504 && (r = fcntl(fptr->fd, F_GETFL)) != -1 &&
505 !(r & O_NONBLOCK)
506 #endif
508 fptr->mode |= FMODE_WSPLIT;
510 fptr->mode |= FMODE_WSPLIT_INITIALIZED;
512 return fptr->mode & FMODE_WSPLIT;
515 struct io_internal_struct {
516 int fd;
517 void *buf;
518 size_t capa;
521 static VALUE
522 internal_read_func(void *ptr)
524 struct io_internal_struct *iis = (struct io_internal_struct*)ptr;
525 return read(iis->fd, iis->buf, iis->capa);
528 static VALUE
529 internal_write_func(void *ptr)
531 struct io_internal_struct *iis = (struct io_internal_struct*)ptr;
532 return write(iis->fd, iis->buf, iis->capa);
535 static int
536 rb_read_internal(int fd, void *buf, size_t count)
538 struct io_internal_struct iis;
539 iis.fd = fd;
540 iis.buf = buf;
541 iis.capa = count;
543 return rb_thread_blocking_region(internal_read_func, &iis, RB_UBF_DFL, 0);
546 static int
547 rb_write_internal(int fd, void *buf, size_t count)
549 struct io_internal_struct iis;
550 iis.fd = fd;
551 iis.buf = buf;
552 iis.capa = count;
554 return rb_thread_blocking_region(internal_write_func, &iis, RB_UBF_DFL, 0);
557 static int
558 io_fflush(rb_io_t *fptr)
560 int r, l;
561 int wbuf_off, wbuf_len;
563 rb_io_check_closed(fptr);
564 if (fptr->wbuf_len == 0)
565 return 0;
566 if (!rb_thread_fd_writable(fptr->fd)) {
567 rb_io_check_closed(fptr);
569 retry:
570 if (fptr->wbuf_len == 0)
571 return 0;
572 wbuf_off = fptr->wbuf_off;
573 wbuf_len = fptr->wbuf_len;
574 l = wbuf_len;
575 if (PIPE_BUF < l &&
576 !rb_thread_critical &&
577 !rb_thread_alone() &&
578 wsplit_p(fptr)) {
579 l = PIPE_BUF;
581 r = rb_write_internal(fptr->fd, fptr->wbuf+wbuf_off, l);
582 /* xxx: Other threads may modify wbuf.
583 * A lock is required, definitely. */
584 rb_io_check_closed(fptr);
585 if (fptr->wbuf_len <= r) {
586 fptr->wbuf_off = 0;
587 fptr->wbuf_len = 0;
588 return 0;
590 if (0 <= r) {
591 fptr->wbuf_off += r;
592 fptr->wbuf_len -= r;
593 errno = EAGAIN;
595 if (rb_io_wait_writable(fptr->fd)) {
596 rb_io_check_closed(fptr);
597 goto retry;
599 return -1;
602 #ifdef HAVE_RB_FD_INIT
603 static VALUE
604 wait_readable(VALUE p)
606 rb_fdset_t *rfds = (rb_fdset_t *)p;
608 return rb_thread_select(rb_fd_max(rfds), rb_fd_ptr(rfds), NULL, NULL, NULL);
610 #endif
613 rb_io_wait_readable(int f)
615 rb_fdset_t rfds;
617 if (f < 0) {
618 rb_raise(rb_eIOError, "closed stream");
620 switch (errno) {
621 case EINTR:
622 #if defined(ERESTART)
623 case ERESTART:
624 #endif
625 rb_thread_wait_fd(f);
626 return Qtrue;
628 case EAGAIN:
629 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
630 case EWOULDBLOCK:
631 #endif
632 rb_fd_init(&rfds);
633 rb_fd_set(f, &rfds);
634 #ifdef HAVE_RB_FD_INIT
635 rb_ensure(wait_readable, (VALUE)&rfds,
636 (VALUE (*)(VALUE))rb_fd_term, (VALUE)&rfds);
637 #else
638 rb_thread_select(f + 1, &rfds, NULL, NULL, NULL);
639 #endif
640 return Qtrue;
642 default:
643 return Qfalse;
647 #ifdef HAVE_RB_FD_INIT
648 static VALUE
649 wait_writable(VALUE p)
651 rb_fdset_t *wfds = (rb_fdset_t *)p;
653 return rb_thread_select(rb_fd_max(wfds), NULL, rb_fd_ptr(wfds), NULL, NULL);
655 #endif
658 rb_io_wait_writable(int f)
660 rb_fdset_t wfds;
662 if (f < 0) {
663 rb_raise(rb_eIOError, "closed stream");
665 switch (errno) {
666 case EINTR:
667 #if defined(ERESTART)
668 case ERESTART:
669 #endif
670 rb_thread_fd_writable(f);
671 return Qtrue;
673 case EAGAIN:
674 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
675 case EWOULDBLOCK:
676 #endif
677 rb_fd_init(&wfds);
678 rb_fd_set(f, &wfds);
679 #ifdef HAVE_RB_FD_INIT
680 rb_ensure(wait_writable, (VALUE)&wfds,
681 (VALUE (*)(VALUE))rb_fd_term, (VALUE)&wfds);
682 #else
683 rb_thread_select(f + 1, NULL, &wfds, NULL, NULL);
684 #endif
685 return Qtrue;
687 default:
688 return Qfalse;
692 /* writing functions */
693 static long
694 io_fwrite(VALUE str, rb_io_t *fptr)
696 long len, n, r, l, offset = 0;
699 * If an external encoding was specified and it differs from
700 * the strings encoding then we must transcode before writing.
701 * We must also transcode if two encodings were specified
703 if (fptr->enc) {
704 /* transcode str before output */
705 /* the methods in transcode.c are static, so call indirectly */
706 /* Can't use encode! because puts writes a frozen newline */
707 if (fptr->enc2) {
708 str = rb_funcall(str, id_encode, 2,
709 rb_enc_from_encoding(fptr->enc2),
710 rb_enc_from_encoding(fptr->enc));
712 else {
713 str = rb_funcall(str, id_encode, 1,
714 rb_enc_from_encoding(fptr->enc));
718 len = RSTRING_LEN(str);
719 if ((n = len) <= 0) return n;
720 if (fptr->wbuf == NULL && !(fptr->mode & FMODE_SYNC)) {
721 fptr->wbuf_off = 0;
722 fptr->wbuf_len = 0;
723 fptr->wbuf_capa = 8192;
724 fptr->wbuf = ALLOC_N(char, fptr->wbuf_capa);
726 if ((fptr->mode & (FMODE_SYNC|FMODE_TTY)) ||
727 (fptr->wbuf && fptr->wbuf_capa <= fptr->wbuf_len + len)) {
728 /* xxx: use writev to avoid double write if available */
729 if (fptr->wbuf_len && fptr->wbuf_len+len <= fptr->wbuf_capa) {
730 if (fptr->wbuf_capa < fptr->wbuf_off+fptr->wbuf_len+len) {
731 MEMMOVE(fptr->wbuf, fptr->wbuf+fptr->wbuf_off, char, fptr->wbuf_len);
732 fptr->wbuf_off = 0;
734 MEMMOVE(fptr->wbuf+fptr->wbuf_off+fptr->wbuf_len, RSTRING_PTR(str)+offset, char, len);
735 fptr->wbuf_len += len;
736 n = 0;
738 if (io_fflush(fptr) < 0)
739 return -1L;
740 if (n == 0)
741 return len;
742 /* avoid context switch between "a" and "\n" in STDERR.puts "a".
743 [ruby-dev:25080] */
744 if (fptr->stdio_file != stderr && !rb_thread_fd_writable(fptr->fd)) {
745 rb_io_check_closed(fptr);
747 retry:
748 l = n;
749 if (PIPE_BUF < l &&
750 !rb_thread_critical &&
751 !rb_thread_alone() &&
752 wsplit_p(fptr)) {
753 l = PIPE_BUF;
755 r = rb_write_internal(fptr->fd, RSTRING_PTR(str)+offset, l);
756 /* xxx: other threads may modify given string. */
757 if (r == n) return len;
758 if (0 <= r) {
759 offset += r;
760 n -= r;
761 errno = EAGAIN;
763 if (rb_io_wait_writable(fptr->fd)) {
764 rb_io_check_closed(fptr);
765 if (offset < RSTRING_LEN(str))
766 goto retry;
768 return -1L;
771 if (fptr->wbuf_off) {
772 if (fptr->wbuf_len)
773 MEMMOVE(fptr->wbuf, fptr->wbuf+fptr->wbuf_off, char, fptr->wbuf_len);
774 fptr->wbuf_off = 0;
776 MEMMOVE(fptr->wbuf+fptr->wbuf_off+fptr->wbuf_len, RSTRING_PTR(str)+offset, char, len);
777 fptr->wbuf_len += len;
778 return len;
781 long
782 rb_io_fwrite(const char *ptr, long len, FILE *f)
784 rb_io_t of;
786 of.fd = fileno(f);
787 of.stdio_file = f;
788 of.mode = FMODE_WRITABLE;
789 of.path = NULL;
790 return io_fwrite(rb_str_new(ptr, len), &of);
794 * call-seq:
795 * ios.write(string) => integer
797 * Writes the given string to <em>ios</em>. The stream must be opened
798 * for writing. If the argument is not a string, it will be converted
799 * to a string using <code>to_s</code>. Returns the number of bytes
800 * written.
802 * count = $stdout.write( "This is a test\n" )
803 * puts "That was #{count} bytes of data"
805 * <em>produces:</em>
807 * This is a test
808 * That was 15 bytes of data
811 static VALUE
812 io_write(VALUE io, VALUE str)
814 rb_io_t *fptr;
815 long n;
816 VALUE tmp;
818 rb_secure(4);
819 io = GetWriteIO(io);
820 str = rb_obj_as_string(str);
821 tmp = rb_io_check_io(io);
822 if (NIL_P(tmp)) {
823 /* port is not IO, call write method for it. */
824 return rb_funcall(io, id_write, 1, str);
826 io = tmp;
827 if (RSTRING_LEN(str) == 0) return INT2FIX(0);
829 GetOpenFile(io, fptr);
830 rb_io_check_writable(fptr);
832 n = io_fwrite(str, fptr);
833 if (n == -1L) rb_sys_fail(fptr->path);
835 return LONG2FIX(n);
838 VALUE
839 rb_io_write(VALUE io, VALUE str)
841 return rb_funcall(io, id_write, 1, str);
845 * call-seq:
846 * ios << obj => ios
848 * String Output---Writes <i>obj</i> to <em>ios</em>.
849 * <i>obj</i> will be converted to a string using
850 * <code>to_s</code>.
852 * $stdout << "Hello " << "world!\n"
854 * <em>produces:</em>
856 * Hello world!
860 VALUE
861 rb_io_addstr(VALUE io, VALUE str)
863 rb_io_write(io, str);
864 return io;
868 * call-seq:
869 * ios.flush => ios
871 * Flushes any buffered data within <em>ios</em> to the underlying
872 * operating system (note that this is Ruby internal buffering only;
873 * the OS may buffer the data as well).
875 * $stdout.print "no newline"
876 * $stdout.flush
878 * <em>produces:</em>
880 * no newline
883 VALUE
884 rb_io_flush(VALUE io)
886 rb_io_t *fptr;
888 if (TYPE(io) != T_FILE) {
889 return rb_funcall(io, id_flush, 0);
892 io = GetWriteIO(io);
893 GetOpenFile(io, fptr);
895 if (fptr->mode & FMODE_WRITABLE) {
896 io_fflush(fptr);
898 if (fptr->mode & FMODE_READABLE) {
899 io_unread(fptr);
902 return io;
906 * call-seq:
907 * ios.pos => integer
908 * ios.tell => integer
910 * Returns the current offset (in bytes) of <em>ios</em>.
912 * f = File.new("testfile")
913 * f.pos #=> 0
914 * f.gets #=> "This is line one\n"
915 * f.pos #=> 17
918 static VALUE
919 rb_io_tell(VALUE io)
921 rb_io_t *fptr;
922 off_t pos;
924 GetOpenFile(io, fptr);
925 pos = io_tell(fptr);
926 if (pos < 0 && errno) rb_sys_fail(fptr->path);
927 return OFFT2NUM(pos);
930 static VALUE
931 rb_io_seek(VALUE io, VALUE offset, int whence)
933 rb_io_t *fptr;
934 off_t pos;
936 pos = NUM2OFFT(offset);
937 GetOpenFile(io, fptr);
938 pos = io_seek(fptr, pos, whence);
939 if (pos < 0 && errno) rb_sys_fail(fptr->path);
941 return INT2FIX(0);
945 * call-seq:
946 * ios.seek(amount, whence=SEEK_SET) -> 0
948 * Seeks to a given offset <i>anInteger</i> in the stream according to
949 * the value of <i>whence</i>:
951 * IO::SEEK_CUR | Seeks to _amount_ plus current position
952 * --------------+----------------------------------------------------
953 * IO::SEEK_END | Seeks to _amount_ plus end of stream (you probably
954 * | want a negative value for _amount_)
955 * --------------+----------------------------------------------------
956 * IO::SEEK_SET | Seeks to the absolute location given by _amount_
958 * Example:
960 * f = File.new("testfile")
961 * f.seek(-13, IO::SEEK_END) #=> 0
962 * f.readline #=> "And so on...\n"
965 static VALUE
966 rb_io_seek_m(int argc, VALUE *argv, VALUE io)
968 VALUE offset, ptrname;
969 int whence = SEEK_SET;
971 if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) {
972 whence = NUM2INT(ptrname);
975 return rb_io_seek(io, offset, whence);
979 * call-seq:
980 * ios.pos = integer => integer
982 * Seeks to the given position (in bytes) in <em>ios</em>.
984 * f = File.new("testfile")
985 * f.pos = 17
986 * f.gets #=> "This is line two\n"
989 static VALUE
990 rb_io_set_pos(VALUE io, VALUE offset)
992 rb_io_t *fptr;
993 off_t pos;
995 pos = NUM2OFFT(offset);
996 GetOpenFile(io, fptr);
997 pos = io_seek(fptr, pos, SEEK_SET);
998 if (pos < 0) rb_sys_fail(fptr->path);
1000 return OFFT2NUM(pos);
1004 * call-seq:
1005 * ios.rewind => 0
1007 * Positions <em>ios</em> to the beginning of input, resetting
1008 * <code>lineno</code> to zero.
1010 * f = File.new("testfile")
1011 * f.readline #=> "This is line one\n"
1012 * f.rewind #=> 0
1013 * f.lineno #=> 0
1014 * f.readline #=> "This is line one\n"
1017 static VALUE
1018 rb_io_rewind(VALUE io)
1020 rb_io_t *fptr;
1022 GetOpenFile(io, fptr);
1023 if (io_seek(fptr, 0L, 0) < 0) rb_sys_fail(fptr->path);
1024 if (io == ARGF.current_file) {
1025 ARGF.gets_lineno -= fptr->lineno;
1027 fptr->lineno = 0;
1029 return INT2FIX(0);
1032 static int
1033 io_fillbuf(rb_io_t *fptr)
1035 int r;
1037 if (fptr->rbuf == NULL) {
1038 fptr->rbuf_off = 0;
1039 fptr->rbuf_len = 0;
1040 fptr->rbuf_capa = 8192;
1041 fptr->rbuf = ALLOC_N(char, fptr->rbuf_capa);
1043 if (fptr->rbuf_len == 0) {
1044 retry:
1046 r = rb_read_internal(fptr->fd, fptr->rbuf, fptr->rbuf_capa);
1048 if (r < 0) {
1049 if (rb_io_wait_readable(fptr->fd))
1050 goto retry;
1051 rb_sys_fail(fptr->path);
1053 fptr->rbuf_off = 0;
1054 fptr->rbuf_len = r;
1055 if (r == 0)
1056 return -1; /* EOF */
1058 return 0;
1062 * call-seq:
1063 * ios.eof => true or false
1064 * ios.eof? => true or false
1066 * Returns true if <em>ios</em> is at end of file that means
1067 * there are no more data to read.
1068 * The stream must be opened for reading or an <code>IOError</code> will be
1069 * raised.
1071 * f = File.new("testfile")
1072 * dummy = f.readlines
1073 * f.eof #=> true
1075 * If <em>ios</em> is a stream such as pipe or socket, <code>IO#eof?</code>
1076 * blocks until the other end sends some data or closes it.
1078 * r, w = IO.pipe
1079 * Thread.new { sleep 1; w.close }
1080 * r.eof? #=> true after 1 second blocking
1082 * r, w = IO.pipe
1083 * Thread.new { sleep 1; w.puts "a" }
1084 * r.eof? #=> false after 1 second blocking
1086 * r, w = IO.pipe
1087 * r.eof? # blocks forever
1089 * Note that <code>IO#eof?</code> reads data to a input buffer.
1090 * So <code>IO#sysread</code> doesn't work with <code>IO#eof?</code>.
1093 VALUE
1094 rb_io_eof(VALUE io)
1096 rb_io_t *fptr;
1098 GetOpenFile(io, fptr);
1099 rb_io_check_readable(fptr);
1101 if (READ_DATA_PENDING(fptr)) return Qfalse;
1102 READ_CHECK(fptr);
1103 if (io_fillbuf(fptr) < 0) {
1104 return Qtrue;
1106 return Qfalse;
1110 * call-seq:
1111 * ios.sync => true or false
1113 * Returns the current ``sync mode'' of <em>ios</em>. When sync mode is
1114 * true, all output is immediately flushed to the underlying operating
1115 * system and is not buffered by Ruby internally. See also
1116 * <code>IO#fsync</code>.
1118 * f = File.new("testfile")
1119 * f.sync #=> false
1122 static VALUE
1123 rb_io_sync(VALUE io)
1125 rb_io_t *fptr;
1127 io = GetWriteIO(io);
1128 GetOpenFile(io, fptr);
1129 return (fptr->mode & FMODE_SYNC) ? Qtrue : Qfalse;
1133 * call-seq:
1134 * ios.sync = boolean => boolean
1136 * Sets the ``sync mode'' to <code>true</code> or <code>false</code>.
1137 * When sync mode is true, all output is immediately flushed to the
1138 * underlying operating system and is not buffered internally. Returns
1139 * the new state. See also <code>IO#fsync</code>.
1141 * f = File.new("testfile")
1142 * f.sync = true
1144 * <em>(produces no output)</em>
1147 static VALUE
1148 rb_io_set_sync(VALUE io, VALUE mode)
1150 rb_io_t *fptr;
1152 io = GetWriteIO(io);
1153 GetOpenFile(io, fptr);
1154 if (RTEST(mode)) {
1155 fptr->mode |= FMODE_SYNC;
1157 else {
1158 fptr->mode &= ~FMODE_SYNC;
1160 return mode;
1164 * call-seq:
1165 * ios.fsync => 0 or nil
1167 * Immediately writes all buffered data in <em>ios</em> to disk.
1168 * Returns <code>nil</code> if the underlying operating system does not
1169 * support <em>fsync(2)</em>. Note that <code>fsync</code> differs from
1170 * using <code>IO#sync=</code>. The latter ensures that data is flushed
1171 * from Ruby's buffers, but doesn't not guarantee that the underlying
1172 * operating system actually writes it to disk.
1175 static VALUE
1176 rb_io_fsync(VALUE io)
1178 #ifdef HAVE_FSYNC
1179 rb_io_t *fptr;
1181 io = GetWriteIO(io);
1182 GetOpenFile(io, fptr);
1184 io_fflush(fptr);
1185 if (fsync(fptr->fd) < 0)
1186 rb_sys_fail(fptr->path);
1187 return INT2FIX(0);
1188 #else
1189 rb_notimplement();
1190 return Qnil; /* not reached */
1191 #endif
1195 * call-seq:
1196 * ios.fileno => fixnum
1197 * ios.to_i => fixnum
1199 * Returns an integer representing the numeric file descriptor for
1200 * <em>ios</em>.
1202 * $stdin.fileno #=> 0
1203 * $stdout.fileno #=> 1
1206 static VALUE
1207 rb_io_fileno(VALUE io)
1209 rb_io_t *fptr;
1210 int fd;
1212 GetOpenFile(io, fptr);
1213 fd = fptr->fd;
1214 return INT2FIX(fd);
1219 * call-seq:
1220 * ios.pid => fixnum
1222 * Returns the process ID of a child process associated with
1223 * <em>ios</em>. This will be set by <code>IO::popen</code>.
1225 * pipe = IO.popen("-")
1226 * if pipe
1227 * $stderr.puts "In parent, child pid is #{pipe.pid}"
1228 * else
1229 * $stderr.puts "In child, pid is #{$$}"
1230 * end
1232 * <em>produces:</em>
1234 * In child, pid is 26209
1235 * In parent, child pid is 26209
1238 static VALUE
1239 rb_io_pid(VALUE io)
1241 rb_io_t *fptr;
1243 GetOpenFile(io, fptr);
1244 if (!fptr->pid)
1245 return Qnil;
1246 return INT2FIX(fptr->pid);
1251 * call-seq:
1252 * ios.inspect => string
1254 * Return a string describing this IO object.
1257 static VALUE
1258 rb_io_inspect(VALUE obj)
1260 rb_io_t *fptr;
1261 const char *cname;
1262 const char *st = "";
1264 fptr = RFILE(rb_io_taint_check(obj))->fptr;
1265 if (!fptr || !fptr->path) return rb_any_to_s(obj);
1266 cname = rb_obj_classname(obj);
1267 if (fptr->fd < 0) {
1268 st = " (closed)";
1270 return rb_sprintf("#<%s:%s%s>", cname, fptr->path, st);
1274 * call-seq:
1275 * ios.to_io -> ios
1277 * Returns <em>ios</em>.
1280 static VALUE
1281 rb_io_to_io(VALUE io)
1283 return io;
1286 /* reading functions */
1287 static long
1288 read_buffered_data(char *ptr, long len, rb_io_t *fptr)
1290 long n;
1292 n = READ_DATA_PENDING_COUNT(fptr);
1293 if (n <= 0) return 0;
1294 if (n > len) n = len;
1295 MEMMOVE(ptr, fptr->rbuf+fptr->rbuf_off, char, n);
1296 fptr->rbuf_off += n;
1297 fptr->rbuf_len -= n;
1298 return n;
1301 static long
1302 io_fread(VALUE str, long offset, rb_io_t *fptr)
1304 long len = RSTRING_LEN(str) - offset;
1305 long n = len;
1306 int c;
1308 if (READ_DATA_PENDING(fptr) == 0) {
1309 while (n > 0) {
1310 c = rb_read_internal(fptr->fd, RSTRING_PTR(str)+offset, n);
1311 if (c == 0) break;
1312 if (c < 0) {
1313 rb_sys_fail(fptr->path);
1315 offset += c;
1316 if ((n -= c) <= 0) break;
1317 rb_thread_wait_fd(fptr->fd);
1319 return len - n;
1322 while (n > 0) {
1323 c = read_buffered_data(RSTRING_PTR(str)+offset, n, fptr);
1324 if (c > 0) {
1325 offset += c;
1326 if ((n -= c) <= 0) break;
1328 rb_thread_wait_fd(fptr->fd);
1329 rb_io_check_closed(fptr);
1330 if (io_fillbuf(fptr) < 0) {
1331 break;
1334 return len - n;
1337 long
1338 rb_io_fread(char *ptr, long len, FILE *f)
1340 rb_io_t of;
1341 VALUE str;
1342 long n;
1344 of.fd = fileno(f);
1345 of.stdio_file = f;
1346 of.mode = FMODE_READABLE;
1347 str = rb_str_new(ptr, len);
1348 n = io_fread(str, 0, &of);
1349 MEMCPY(ptr, RSTRING_PTR(str), char, n);
1350 return n;
1353 #define SMALLBUF 100
1355 static long
1356 remain_size(rb_io_t *fptr)
1358 struct stat st;
1359 off_t siz = READ_DATA_PENDING_COUNT(fptr);
1360 off_t pos;
1362 if (fstat(fptr->fd, &st) == 0 && S_ISREG(st.st_mode)
1363 #ifdef __BEOS__
1364 && (st.st_dev > 3)
1365 #endif
1368 io_fflush(fptr);
1369 pos = lseek(fptr->fd, 0, SEEK_CUR);
1370 if (st.st_size >= pos && pos >= 0) {
1371 siz += st.st_size - pos;
1372 if (siz > LONG_MAX) {
1373 rb_raise(rb_eIOError, "file too big for single read");
1377 else {
1378 siz += BUFSIZ;
1380 return (long)siz;
1383 static VALUE
1384 io_enc_str(VALUE str, rb_io_t *fptr)
1386 OBJ_TAINT(str);
1387 rb_enc_associate(str, io_read_encoding(fptr));
1388 return str;
1391 static void
1392 make_readconv(rb_io_t *fptr)
1394 if (!fptr->readconv) {
1395 fptr->readconv = rb_econv_open(fptr->enc2->name, fptr->enc->name, 0);
1396 if (!fptr->readconv)
1397 rb_raise(rb_eIOError, "code converter open failed (%s to %s)", fptr->enc->name, fptr->enc2->name);
1398 fptr->crbuf_off = 0;
1399 fptr->crbuf_len = 0;
1400 fptr->crbuf_capa = 1024;
1401 fptr->crbuf = ALLOC_N(char, fptr->crbuf_capa);
1405 static int
1406 more_char(rb_io_t *fptr)
1408 const unsigned char *ss, *sp, *se;
1409 unsigned char *ds, *dp, *de;
1410 rb_econv_result_t res;
1411 int putbackable;
1412 int crbuf_len0;
1414 if (fptr->crbuf_len == fptr->crbuf_capa)
1415 return 0; /* crbuf full */
1416 if (fptr->crbuf_len == 0)
1417 fptr->crbuf_off = 0;
1418 else if (fptr->crbuf_off + fptr->crbuf_len == fptr->crbuf_capa) {
1419 memmove(fptr->crbuf, fptr->crbuf+fptr->crbuf_off, fptr->crbuf_len);
1420 fptr->crbuf_off = 0;
1423 crbuf_len0 = fptr->crbuf_len;
1425 while (1) {
1426 ss = sp = (const unsigned char *)fptr->rbuf + fptr->rbuf_off;
1427 se = sp + fptr->rbuf_len;
1428 ds = dp = (unsigned char *)fptr->crbuf + fptr->crbuf_off + fptr->crbuf_len;
1429 de = (unsigned char *)fptr->crbuf + fptr->crbuf_capa;
1430 res = rb_econv_convert(fptr->readconv, &sp, se, &dp, de, ECONV_PARTIAL_INPUT|ECONV_OUTPUT_FOLLOWED_BY_INPUT);
1431 fptr->rbuf_off += sp - ss;
1432 fptr->rbuf_len -= sp - ss;
1433 fptr->crbuf_len += dp - ds;
1435 putbackable = rb_econv_putbackable(fptr->readconv);
1436 if (putbackable) {
1437 rb_econv_putback(fptr->readconv, (unsigned char *)fptr->rbuf + fptr->rbuf_off - putbackable, putbackable);
1438 fptr->rbuf_off -= putbackable;
1439 fptr->rbuf_len += putbackable;
1442 rb_econv_check_error(fptr->readconv);
1444 if (crbuf_len0 != fptr->crbuf_len)
1445 return 0;
1447 if (res == econv_finished)
1448 return -1;
1450 if (res == econv_source_buffer_empty) {
1451 if (fptr->rbuf_len == 0) {
1452 rb_thread_wait_fd(fptr->fd);
1453 rb_io_check_closed(fptr);
1454 if (io_fillbuf(fptr) == -1) {
1455 ds = dp = (unsigned char *)fptr->crbuf + fptr->crbuf_off + fptr->crbuf_len;
1456 de = (unsigned char *)fptr->crbuf + fptr->crbuf_capa;
1457 res = rb_econv_convert(fptr->readconv, NULL, NULL, &dp, de, 0);
1458 fptr->crbuf_len += dp - ds;
1459 rb_econv_check_error(fptr->readconv);
1466 static VALUE
1467 io_shift_crbuf(rb_io_t *fptr, int len, VALUE *strp)
1469 VALUE str;
1470 if (NIL_P(*strp)) {
1471 *strp = str = rb_str_new(fptr->crbuf+fptr->crbuf_off, len);
1473 else {
1474 size_t slen;
1475 str = *strp;
1476 slen = RSTRING_LEN(str);
1477 rb_str_resize(str, RSTRING_LEN(str) + len);
1478 memcpy(RSTRING_PTR(str)+slen, fptr->crbuf+fptr->crbuf_off, len);
1480 fptr->crbuf_off += len;
1481 fptr->crbuf_len -= len;
1482 OBJ_TAINT(str);
1483 rb_enc_associate(str, fptr->enc);
1484 /* xxx: set coderange */
1485 if (fptr->crbuf_len == 0)
1486 fptr->crbuf_off = 0;
1487 if (fptr->crbuf_off < fptr->crbuf_capa/2) {
1488 memmove(fptr->crbuf, fptr->crbuf+fptr->crbuf_off, fptr->crbuf_len);
1489 fptr->crbuf_off = 0;
1491 return str;
1494 static VALUE
1495 read_all(rb_io_t *fptr, long siz, VALUE str)
1497 long bytes;
1498 long n;
1499 long pos;
1500 rb_encoding *enc;
1501 int cr;
1503 if (fptr->enc2) {
1504 VALUE str = rb_str_new(NULL, 0);
1505 make_readconv(fptr);
1506 while (1) {
1507 if (fptr->crbuf_len) {
1508 io_shift_crbuf(fptr, fptr->crbuf_len, &str);
1510 if (more_char(fptr) == -1) {
1511 return io_enc_str(str, fptr);
1516 bytes = 0;
1517 pos = 0;
1519 enc = io_read_encoding(fptr);
1520 cr = fptr->enc2 ? ENC_CODERANGE_BROKEN : 0;
1522 if (siz == 0) siz = BUFSIZ;
1523 if (NIL_P(str)) {
1524 str = rb_str_new(0, siz);
1526 else {
1527 rb_str_resize(str, siz);
1529 for (;;) {
1530 READ_CHECK(fptr);
1531 n = io_fread(str, bytes, fptr);
1532 if (n == 0 && bytes == 0) {
1533 break;
1535 bytes += n;
1536 if (cr != ENC_CODERANGE_BROKEN)
1537 pos = rb_str_coderange_scan_restartable(RSTRING_PTR(str) + pos, RSTRING_PTR(str) + bytes, enc, &cr);
1538 if (bytes < siz) break;
1539 siz += BUFSIZ;
1540 rb_str_resize(str, siz);
1542 if (bytes != siz) rb_str_resize(str, bytes);
1543 str = io_enc_str(str, fptr);
1544 if (!fptr->enc2) {
1545 ENC_CODERANGE_SET(str, cr);
1547 return str;
1550 void
1551 rb_io_set_nonblock(rb_io_t *fptr)
1553 int flags;
1554 #ifdef F_GETFL
1555 flags = fcntl(fptr->fd, F_GETFL);
1556 if (flags == -1) {
1557 rb_sys_fail(fptr->path);
1559 #else
1560 flags = 0;
1561 #endif
1562 if ((flags & O_NONBLOCK) == 0) {
1563 flags |= O_NONBLOCK;
1564 if (fcntl(fptr->fd, F_SETFL, flags) == -1) {
1565 rb_sys_fail(fptr->path);
1570 static VALUE
1571 io_getpartial(int argc, VALUE *argv, VALUE io, int nonblock)
1573 rb_io_t *fptr;
1574 VALUE length, str;
1575 long n, len;
1577 rb_scan_args(argc, argv, "11", &length, &str);
1579 if ((len = NUM2LONG(length)) < 0) {
1580 rb_raise(rb_eArgError, "negative length %ld given", len);
1583 if (NIL_P(str)) {
1584 str = rb_str_new(0, len);
1586 else {
1587 StringValue(str);
1588 rb_str_modify(str);
1589 rb_str_resize(str, len);
1591 OBJ_TAINT(str);
1593 GetOpenFile(io, fptr);
1594 rb_io_check_readable(fptr);
1596 if (len == 0)
1597 return str;
1599 if (!nonblock)
1600 READ_CHECK(fptr);
1601 if (RSTRING_LEN(str) != len) {
1602 modified:
1603 rb_raise(rb_eRuntimeError, "buffer string modified");
1605 n = read_buffered_data(RSTRING_PTR(str), len, fptr);
1606 if (n <= 0) {
1607 again:
1608 if (RSTRING_LEN(str) != len) goto modified;
1609 if (nonblock) {
1610 rb_io_set_nonblock(fptr);
1612 n = rb_read_internal(fptr->fd, RSTRING_PTR(str), len);
1613 if (n < 0) {
1614 if (!nonblock && rb_io_wait_readable(fptr->fd))
1615 goto again;
1616 rb_sys_fail(fptr->path);
1619 rb_str_resize(str, n);
1621 if (n == 0)
1622 return Qnil;
1623 else
1624 return str;
1628 * call-seq:
1629 * ios.readpartial(maxlen) => string
1630 * ios.readpartial(maxlen, outbuf) => outbuf
1632 * Reads at most <i>maxlen</i> bytes from the I/O stream.
1633 * It blocks only if <em>ios</em> has no data immediately available.
1634 * It doesn't block if some data available.
1635 * If the optional <i>outbuf</i> argument is present,
1636 * it must reference a String, which will receive the data.
1637 * It raises <code>EOFError</code> on end of file.
1639 * readpartial is designed for streams such as pipe, socket, tty, etc.
1640 * It blocks only when no data immediately available.
1641 * This means that it blocks only when following all conditions hold.
1642 * * the buffer in the IO object is empty.
1643 * * the content of the stream is empty.
1644 * * the stream is not reached to EOF.
1646 * When readpartial blocks, it waits data or EOF on the stream.
1647 * If some data is reached, readpartial returns with the data.
1648 * If EOF is reached, readpartial raises EOFError.
1650 * When readpartial doesn't blocks, it returns or raises immediately.
1651 * If the buffer is not empty, it returns the data in the buffer.
1652 * Otherwise if the stream has some content,
1653 * it returns the data in the stream.
1654 * Otherwise if the stream is reached to EOF, it raises EOFError.
1656 * r, w = IO.pipe # buffer pipe content
1657 * w << "abc" # "" "abc".
1658 * r.readpartial(4096) #=> "abc" "" ""
1659 * r.readpartial(4096) # blocks because buffer and pipe is empty.
1661 * r, w = IO.pipe # buffer pipe content
1662 * w << "abc" # "" "abc"
1663 * w.close # "" "abc" EOF
1664 * r.readpartial(4096) #=> "abc" "" EOF
1665 * r.readpartial(4096) # raises EOFError
1667 * r, w = IO.pipe # buffer pipe content
1668 * w << "abc\ndef\n" # "" "abc\ndef\n"
1669 * r.gets #=> "abc\n" "def\n" ""
1670 * w << "ghi\n" # "def\n" "ghi\n"
1671 * r.readpartial(4096) #=> "def\n" "" "ghi\n"
1672 * r.readpartial(4096) #=> "ghi\n" "" ""
1674 * Note that readpartial behaves similar to sysread.
1675 * The differences are:
1676 * * If the buffer is not empty, read from the buffer instead of "sysread for buffered IO (IOError)".
1677 * * It doesn't cause Errno::EAGAIN and Errno::EINTR. When readpartial meets EAGAIN and EINTR by read system call, readpartial retry the system call.
1679 * The later means that readpartial is nonblocking-flag insensitive.
1680 * It blocks on the situation IO#sysread causes Errno::EAGAIN as if the fd is blocking mode.
1684 static VALUE
1685 io_readpartial(int argc, VALUE *argv, VALUE io)
1687 VALUE ret;
1689 ret = io_getpartial(argc, argv, io, 0);
1690 if (NIL_P(ret))
1691 rb_eof_error();
1692 else
1693 return ret;
1697 * call-seq:
1698 * ios.read_nonblock(maxlen) => string
1699 * ios.read_nonblock(maxlen, outbuf) => outbuf
1701 * Reads at most <i>maxlen</i> bytes from <em>ios</em> using
1702 * read(2) system call after O_NONBLOCK is set for
1703 * the underlying file descriptor.
1705 * If the optional <i>outbuf</i> argument is present,
1706 * it must reference a String, which will receive the data.
1708 * read_nonblock just calls read(2).
1709 * It causes all errors read(2) causes: EAGAIN, EINTR, etc.
1710 * The caller should care such errors.
1712 * read_nonblock causes EOFError on EOF.
1714 * If the read buffer is not empty,
1715 * read_nonblock reads from the buffer like readpartial.
1716 * In this case, read(2) is not called.
1720 static VALUE
1721 io_read_nonblock(int argc, VALUE *argv, VALUE io)
1723 VALUE ret;
1725 ret = io_getpartial(argc, argv, io, 1);
1726 if (NIL_P(ret))
1727 rb_eof_error();
1728 else
1729 return ret;
1733 * call-seq:
1734 * ios.write_nonblock(string) => integer
1736 * Writes the given string to <em>ios</em> using
1737 * write(2) system call after O_NONBLOCK is set for
1738 * the underlying file descriptor.
1740 * write_nonblock just calls write(2).
1741 * It causes all errors write(2) causes: EAGAIN, EINTR, etc.
1742 * The result may also be smaller than string.length (partial write).
1743 * The caller should care such errors and partial write.
1745 * If the write buffer is not empty, it is flushed at first.
1749 static VALUE
1750 rb_io_write_nonblock(VALUE io, VALUE str)
1752 rb_io_t *fptr;
1753 long n;
1755 rb_secure(4);
1756 if (TYPE(str) != T_STRING)
1757 str = rb_obj_as_string(str);
1759 io = GetWriteIO(io);
1760 GetOpenFile(io, fptr);
1761 rb_io_check_writable(fptr);
1763 io_fflush(fptr);
1765 rb_io_set_nonblock(fptr);
1766 n = write(fptr->fd, RSTRING_PTR(str), RSTRING_LEN(str));
1768 if (n == -1) rb_sys_fail(fptr->path);
1770 return LONG2FIX(n);
1774 * call-seq:
1775 * ios.read([length [, buffer]]) => string, buffer, or nil
1777 * Reads at most <i>length</i> bytes from the I/O stream, or to the
1778 * end of file if <i>length</i> is omitted or is <code>nil</code>.
1779 * <i>length</i> must be a non-negative integer or nil.
1780 * If the optional <i>buffer</i> argument is present, it must reference
1781 * a String, which will receive the data.
1783 * At end of file, it returns <code>nil</code> or <code>""</code>
1784 * depend on <i>length</i>.
1785 * <code><i>ios</i>.read()</code> and
1786 * <code><i>ios</i>.read(nil)</code> returns <code>""</code>.
1787 * <code><i>ios</i>.read(<i>positive-integer</i>)</code> returns nil.
1789 * <code><i>ios</i>.read(0)</code> returns <code>""</code>.
1791 * f = File.new("testfile")
1792 * f.read(16) #=> "This is line one"
1795 static VALUE
1796 io_read(int argc, VALUE *argv, VALUE io)
1798 rb_io_t *fptr;
1799 long n, len;
1800 VALUE length, str;
1802 rb_scan_args(argc, argv, "02", &length, &str);
1804 if (NIL_P(length)) {
1805 if (!NIL_P(str)) StringValue(str);
1806 GetOpenFile(io, fptr);
1807 rb_io_check_readable(fptr);
1808 return read_all(fptr, remain_size(fptr), str);
1810 len = NUM2LONG(length);
1811 if (len < 0) {
1812 rb_raise(rb_eArgError, "negative length %ld given", len);
1815 if (NIL_P(str)) {
1816 str = rb_str_new(0, len);
1818 else {
1819 StringValue(str);
1820 rb_str_modify(str);
1821 rb_str_resize(str,len);
1824 GetOpenFile(io, fptr);
1825 rb_io_check_readable(fptr);
1826 if (len == 0) return str;
1828 READ_CHECK(fptr);
1829 if (RSTRING_LEN(str) != len) {
1830 rb_raise(rb_eRuntimeError, "buffer string modified");
1832 n = io_fread(str, 0, fptr);
1833 if (n == 0) {
1834 if (fptr->fd < 0) return Qnil;
1835 rb_str_resize(str, 0);
1836 return Qnil;
1838 rb_str_resize(str, n);
1840 return str;
1843 static void
1844 rscheck(const char *rsptr, long rslen, VALUE rs)
1846 if (!rs) return;
1847 if (RSTRING_PTR(rs) != rsptr && RSTRING_LEN(rs) != rslen)
1848 rb_raise(rb_eRuntimeError, "rs modified");
1851 static int
1852 appendline(rb_io_t *fptr, int delim, VALUE *strp, long *lp)
1854 VALUE str = *strp;
1855 long limit = *lp;
1857 if (fptr->enc2) {
1858 make_readconv(fptr);
1859 while (1) {
1860 const char *p, *e;
1861 int searchlen;
1862 if (fptr->crbuf_len) {
1863 p = fptr->crbuf+fptr->crbuf_off;
1864 searchlen = fptr->crbuf_len;
1865 if (0 < limit && limit < searchlen)
1866 searchlen = limit;
1867 e = memchr(p, delim, searchlen);
1868 if (e) {
1869 if (NIL_P(str))
1870 *strp = str = rb_str_new(p, e-p+1);
1871 else
1872 rb_str_buf_cat(str, p, e-p+1);
1873 fptr->crbuf_off += e-p+1;
1874 fptr->crbuf_len -= e-p+1;
1875 limit -= e-p+1;
1876 *lp = limit;
1877 return delim;
1880 if (NIL_P(str))
1881 *strp = str = rb_str_new(p, searchlen);
1882 else
1883 rb_str_buf_cat(str, p, searchlen);
1884 fptr->crbuf_off += searchlen;
1885 fptr->crbuf_len -= searchlen;
1886 limit -= searchlen;
1888 if (limit == 0) {
1889 *lp = limit;
1890 return (unsigned char)RSTRING_PTR(str)[RSTRING_LEN(str)-1];
1894 if (more_char(fptr) == -1) {
1895 *lp = limit;
1896 return EOF;
1901 while (1) {
1902 long pending = READ_DATA_PENDING_COUNT(fptr);
1903 if (pending > 0) {
1904 const char *p = READ_DATA_PENDING_PTR(fptr);
1905 const char *e;
1906 long last;
1908 if (limit > 0 && pending > limit) pending = limit;
1909 e = memchr(p, delim, pending);
1910 if (e) pending = e - p + 1;
1911 if (!NIL_P(str)) {
1912 last = RSTRING_LEN(str);
1913 rb_str_resize(str, last + pending);
1915 else {
1916 last = 0;
1917 *strp = str = rb_str_buf_new(pending);
1918 rb_str_set_len(str, pending);
1920 read_buffered_data(RSTRING_PTR(str) + last, pending, fptr); /* must not fail */
1921 limit -= pending;
1922 *lp = limit;
1923 if (e) return delim;
1924 if (limit == 0)
1925 return (unsigned char)RSTRING_PTR(str)[RSTRING_LEN(str)-1];
1927 rb_thread_wait_fd(fptr->fd);
1928 rb_io_check_closed(fptr);
1929 if (io_fillbuf(fptr) < 0) {
1930 *lp = limit;
1931 return EOF;
1936 static inline int
1937 swallow(rb_io_t *fptr, int term)
1939 do {
1940 long cnt;
1941 while ((cnt = READ_DATA_PENDING_COUNT(fptr)) > 0) {
1942 char buf[1024];
1943 const char *p = READ_DATA_PENDING_PTR(fptr);
1944 int i;
1945 if (cnt > sizeof buf) cnt = sizeof buf;
1946 if (*p != term) return Qtrue;
1947 i = cnt;
1948 while (--i && *++p == term);
1949 if (!read_buffered_data(buf, cnt - i, fptr)) /* must not fail */
1950 rb_sys_fail(fptr->path);
1952 rb_thread_wait_fd(fptr->fd);
1953 rb_io_check_closed(fptr);
1954 } while (io_fillbuf(fptr) == 0);
1955 return Qfalse;
1958 static VALUE
1959 rb_io_getline_fast(rb_io_t *fptr, rb_encoding *enc)
1961 VALUE str = Qnil;
1962 int len = 0;
1963 long pos = 0;
1964 int cr = fptr->enc2 ? ENC_CODERANGE_BROKEN : 0;
1966 for (;;) {
1967 long pending = READ_DATA_PENDING_COUNT(fptr);
1969 if (pending > 0) {
1970 const char *p = READ_DATA_PENDING_PTR(fptr);
1971 const char *e;
1973 e = memchr(p, '\n', pending);
1974 if (e) {
1975 pending = e - p + 1;
1977 if (NIL_P(str)) {
1978 str = rb_str_new(p, pending);
1979 fptr->rbuf_off += pending;
1980 fptr->rbuf_len -= pending;
1982 else {
1983 rb_str_resize(str, len + pending);
1984 read_buffered_data(RSTRING_PTR(str)+len, pending, fptr);
1986 len += pending;
1987 if (cr != ENC_CODERANGE_BROKEN)
1988 pos = rb_str_coderange_scan_restartable(RSTRING_PTR(str) + pos, RSTRING_PTR(str) + len, enc, &cr);
1989 if (e) break;
1991 rb_thread_wait_fd(fptr->fd);
1992 rb_io_check_closed(fptr);
1993 if (io_fillbuf(fptr) < 0) {
1994 if (NIL_P(str)) return Qnil;
1995 break;
1999 str = io_enc_str(str, fptr);
2000 if (!fptr->enc2) ENC_CODERANGE_SET(str, cr);
2001 fptr->lineno++;
2002 ARGF.lineno = INT2FIX(fptr->lineno);
2003 return str;
2006 static void
2007 prepare_getline_args(int argc, VALUE *argv, VALUE *rsp, long *limit, VALUE io)
2009 VALUE rs = rb_rs, lim = Qnil;
2010 rb_io_t *fptr;
2012 if (argc == 1) {
2013 VALUE tmp = Qnil;
2015 if (NIL_P(argv[0]) || !NIL_P(tmp = rb_check_string_type(argv[0]))) {
2016 rs = tmp;
2018 else {
2019 lim = argv[0];
2022 else if (2 <= argc) {
2023 rb_scan_args(argc, argv, "2", &rs, &lim);
2024 if (!NIL_P(rs))
2025 StringValue(rs);
2027 if (!NIL_P(rs)) {
2028 rb_encoding *enc_rs, *enc_io;
2030 GetOpenFile(io, fptr);
2031 enc_rs = rb_enc_get(rs);
2032 enc_io = io_read_encoding(fptr);
2033 if (enc_io != enc_rs &&
2034 (rb_enc_str_coderange(rs) != ENC_CODERANGE_7BIT ||
2035 !rb_enc_asciicompat(enc_io))) {
2036 if (rs == rb_default_rs) {
2037 rs = rb_enc_str_new(0, 0, enc_io);
2038 rb_str_buf_cat_ascii(rs, "\n");
2040 else {
2041 rb_raise(rb_eArgError, "encoding mismatch: %s IO with %s RS",
2042 rb_enc_name(enc_io),
2043 rb_enc_name(enc_rs));
2047 *rsp = rs;
2048 *limit = NIL_P(lim) ? -1L : NUM2LONG(lim);
2051 static VALUE
2052 rb_io_getline_1(VALUE rs, long limit, VALUE io)
2054 VALUE str = Qnil;
2055 rb_io_t *fptr;
2056 int nolimit = 0;
2057 rb_encoding *enc;
2059 GetOpenFile(io, fptr);
2060 rb_io_check_readable(fptr);
2061 if (NIL_P(rs)) {
2062 str = read_all(fptr, 0, Qnil);
2063 if (RSTRING_LEN(str) == 0) return Qnil;
2065 else if (limit == 0) {
2066 return rb_enc_str_new(0, 0, io_read_encoding(fptr));
2068 else if (rs == rb_default_rs && limit < 0 && !fptr->enc2 &&
2069 rb_enc_asciicompat(enc = io_read_encoding(fptr))) {
2070 return rb_io_getline_fast(fptr, enc);
2072 else {
2073 int c, newline;
2074 const char *rsptr;
2075 long rslen;
2076 int rspara = 0;
2077 int extra_limit = 16;
2079 rslen = RSTRING_LEN(rs);
2080 if (rslen == 0) {
2081 rsptr = "\n\n";
2082 rslen = 2;
2083 rspara = 1;
2084 swallow(fptr, '\n');
2085 rs = 0;
2087 else {
2088 rsptr = RSTRING_PTR(rs);
2090 newline = (unsigned char)rsptr[rslen - 1];
2092 if (fptr->enc2)
2093 enc = fptr->enc;
2094 else
2095 enc = io_input_encoding(fptr);
2096 while ((c = appendline(fptr, newline, &str, &limit)) != EOF) {
2097 const char *s, *p, *pp;
2099 if (c == newline) {
2100 if (RSTRING_LEN(str) < rslen) continue;
2101 s = RSTRING_PTR(str);
2102 p = s + RSTRING_LEN(str) - rslen;
2103 pp = rb_enc_left_char_head(s, p, enc);
2104 if (pp != p) continue;
2105 if (!rspara) rscheck(rsptr, rslen, rs);
2106 if (memcmp(p, rsptr, rslen) == 0) break;
2108 if (limit == 0) {
2109 s = RSTRING_PTR(str);
2110 p = s + RSTRING_LEN(str);
2111 pp = rb_enc_left_char_head(s, p-1, enc);
2112 if (extra_limit &&
2113 MBCLEN_NEEDMORE_P(rb_enc_precise_mbclen(pp, p, enc))) {
2114 /* relax the limit while incomplete character.
2115 * extra_limit limits the relax length */
2116 limit = 1;
2117 extra_limit--;
2119 else {
2120 nolimit = 1;
2121 break;
2126 if (rspara) {
2127 if (c != EOF) {
2128 swallow(fptr, '\n');
2131 if (!NIL_P(str))
2132 str = io_enc_str(str, fptr);
2135 if (!NIL_P(str)) {
2136 if (!nolimit) {
2137 fptr->lineno++;
2138 ARGF.lineno = INT2FIX(fptr->lineno);
2142 return str;
2145 static VALUE
2146 rb_io_getline(int argc, VALUE *argv, VALUE io)
2148 VALUE rs;
2149 long limit;
2151 prepare_getline_args(argc, argv, &rs, &limit, io);
2152 return rb_io_getline_1(rs, limit, io);
2155 VALUE
2156 rb_io_gets(VALUE io)
2158 rb_io_t *fptr;
2160 GetOpenFile(io, fptr);
2161 rb_io_check_readable(fptr);
2162 return rb_io_getline_fast(fptr, io_read_encoding(fptr));
2166 * call-seq:
2167 * ios.gets(sep=$/) => string or nil
2168 * ios.gets(limit) => string or nil
2169 * ios.gets(sep, limit) => string or nil
2171 * Reads the next ``line'' from the I/O stream; lines are separated by
2172 * <i>sep</i>. A separator of <code>nil</code> reads the entire
2173 * contents, and a zero-length separator reads the input a paragraph at
2174 * a time (two successive newlines in the input separate paragraphs).
2175 * The stream must be opened for reading or an <code>IOError</code>
2176 * will be raised. The line read in will be returned and also assigned
2177 * to <code>$_</code>. Returns <code>nil</code> if called at end of
2178 * file. If the first argument is an integer, or optional second
2179 * argument is given, the returning string would not be longer than the
2180 * given value.
2182 * File.new("testfile").gets #=> "This is line one\n"
2183 * $_ #=> "This is line one\n"
2186 static VALUE
2187 rb_io_gets_m(int argc, VALUE *argv, VALUE io)
2189 VALUE str;
2191 str = rb_io_getline(argc, argv, io);
2192 rb_lastline_set(str);
2194 return str;
2198 * call-seq:
2199 * ios.lineno => integer
2201 * Returns the current line number in <em>ios</em>. The stream must be
2202 * opened for reading. <code>lineno</code> counts the number of times
2203 * <code>gets</code> is called, rather than the number of newlines
2204 * encountered. The two values will differ if <code>gets</code> is
2205 * called with a separator other than newline. See also the
2206 * <code>$.</code> variable.
2208 * f = File.new("testfile")
2209 * f.lineno #=> 0
2210 * f.gets #=> "This is line one\n"
2211 * f.lineno #=> 1
2212 * f.gets #=> "This is line two\n"
2213 * f.lineno #=> 2
2216 static VALUE
2217 rb_io_lineno(VALUE io)
2219 rb_io_t *fptr;
2221 GetOpenFile(io, fptr);
2222 rb_io_check_readable(fptr);
2223 return INT2NUM(fptr->lineno);
2227 * call-seq:
2228 * ios.lineno = integer => integer
2230 * Manually sets the current line number to the given value.
2231 * <code>$.</code> is updated only on the next read.
2233 * f = File.new("testfile")
2234 * f.gets #=> "This is line one\n"
2235 * $. #=> 1
2236 * f.lineno = 1000
2237 * f.lineno #=> 1000
2238 * $. #=> 1 # lineno of last read
2239 * f.gets #=> "This is line two\n"
2240 * $. #=> 1001 # lineno of last read
2243 static VALUE
2244 rb_io_set_lineno(VALUE io, VALUE lineno)
2246 rb_io_t *fptr;
2248 GetOpenFile(io, fptr);
2249 rb_io_check_readable(fptr);
2250 fptr->lineno = NUM2INT(lineno);
2251 return lineno;
2255 * call-seq:
2256 * ios.readline(sep=$/) => string
2257 * ios.readline(limit) => string
2258 * ios.readline(sep, limit) => string
2260 * Reads a line as with <code>IO#gets</code>, but raises an
2261 * <code>EOFError</code> on end of file.
2264 static VALUE
2265 rb_io_readline(int argc, VALUE *argv, VALUE io)
2267 VALUE line = rb_io_gets_m(argc, argv, io);
2269 if (NIL_P(line)) {
2270 rb_eof_error();
2272 return line;
2276 * call-seq:
2277 * ios.readlines(sep=$/) => array
2278 * ios.readlines(limit) => array
2279 * ios.readlines(sep, limit) => array
2281 * Reads all of the lines in <em>ios</em>, and returns them in
2282 * <i>anArray</i>. Lines are separated by the optional <i>sep</i>. If
2283 * <i>sep</i> is <code>nil</code>, the rest of the stream is returned
2284 * as a single record. If the first argument is an integer, or
2285 * optional second argument is given, the returning string would not be
2286 * longer than the given value. The stream must be opened for reading
2287 * or an <code>IOError</code> will be raised.
2289 * f = File.new("testfile")
2290 * f.readlines[0] #=> "This is line one\n"
2293 static VALUE
2294 rb_io_readlines(int argc, VALUE *argv, VALUE io)
2296 VALUE line, ary, rs;
2297 long limit;
2299 prepare_getline_args(argc, argv, &rs, &limit, io);
2300 ary = rb_ary_new();
2301 while (!NIL_P(line = rb_io_getline_1(rs, limit, io))) {
2302 rb_ary_push(ary, line);
2304 return ary;
2308 * call-seq:
2309 * ios.each(sep=$/) {|line| block } => ios
2310 * ios.each(limit) {|line| block } => ios
2311 * ios.each(sep,limit) {|line| block } => ios
2312 * ios.each_line(sep=$/) {|line| block } => ios
2313 * ios.each_line(limit) {|line| block } => ios
2314 * ios.each_line(sep,limit) {|line| block } => ios
2316 * Executes the block for every line in <em>ios</em>, where lines are
2317 * separated by <i>sep</i>. <em>ios</em> must be opened for
2318 * reading or an <code>IOError</code> will be raised.
2320 * f = File.new("testfile")
2321 * f.each {|line| puts "#{f.lineno}: #{line}" }
2323 * <em>produces:</em>
2325 * 1: This is line one
2326 * 2: This is line two
2327 * 3: This is line three
2328 * 4: And so on...
2331 static VALUE
2332 rb_io_each_line(int argc, VALUE *argv, VALUE io)
2334 VALUE str, rs;
2335 long limit;
2337 RETURN_ENUMERATOR(io, argc, argv);
2338 prepare_getline_args(argc, argv, &rs, &limit, io);
2339 while (!NIL_P(str = rb_io_getline_1(rs, limit, io))) {
2340 rb_yield(str);
2342 return io;
2346 * call-seq:
2347 * ios.each_byte {|byte| block } => ios
2349 * Calls the given block once for each byte (0..255) in <em>ios</em>,
2350 * passing the byte as an argument. The stream must be opened for
2351 * reading or an <code>IOError</code> will be raised.
2353 * f = File.new("testfile")
2354 * checksum = 0
2355 * f.each_byte {|x| checksum ^= x } #=> #<File:testfile>
2356 * checksum #=> 12
2359 static VALUE
2360 rb_io_each_byte(VALUE io)
2362 rb_io_t *fptr;
2363 char *p, *e;
2365 RETURN_ENUMERATOR(io, 0, 0);
2366 GetOpenFile(io, fptr);
2368 for (;;) {
2369 p = fptr->rbuf+fptr->rbuf_off;
2370 e = p + fptr->rbuf_len;
2371 while (p < e) {
2372 fptr->rbuf_off++;
2373 fptr->rbuf_len--;
2374 rb_yield(INT2FIX(*p & 0xff));
2375 p++;
2376 errno = 0;
2378 rb_io_check_readable(fptr);
2379 READ_CHECK(fptr);
2380 if (io_fillbuf(fptr) < 0) {
2381 break;
2384 return io;
2387 static VALUE
2388 io_getc(rb_io_t *fptr, rb_encoding *enc)
2390 int r, n, cr = 0;
2391 VALUE str;
2393 if (fptr->enc2) {
2394 VALUE str = Qnil;
2396 if (!fptr->readconv) {
2397 make_readconv(fptr);
2400 while (1) {
2401 if (fptr->crbuf_len) {
2402 r = rb_enc_precise_mbclen(fptr->crbuf+fptr->crbuf_off,
2403 fptr->crbuf+fptr->crbuf_off+fptr->crbuf_len,
2404 fptr->enc);
2405 if (!MBCLEN_NEEDMORE_P(r))
2406 break;
2407 if (fptr->crbuf_len == fptr->crbuf_capa) {
2408 rb_raise(rb_eIOError, "too long character");
2412 if (more_char(fptr) == -1) {
2413 if (fptr->crbuf_len == 0)
2414 return Qnil;
2415 /* return an incomplete character just before EOF */
2416 return io_shift_crbuf(fptr, fptr->crbuf_len, &str);
2419 if (MBCLEN_INVALID_P(r)) {
2420 r = rb_enc_mbclen(fptr->crbuf+fptr->crbuf_off,
2421 fptr->crbuf+fptr->crbuf_off+fptr->crbuf_len,
2422 fptr->enc);
2423 return io_shift_crbuf(fptr, r, &str);
2425 return io_shift_crbuf(fptr, MBCLEN_CHARFOUND_LEN(r), &str);
2428 if (io_fillbuf(fptr) < 0) {
2429 return Qnil;
2431 if (rb_enc_asciicompat(enc) && ISASCII(fptr->rbuf[fptr->rbuf_off])) {
2432 str = rb_str_new(fptr->rbuf+fptr->rbuf_off, 1);
2433 fptr->rbuf_off += 1;
2434 fptr->rbuf_len -= 1;
2435 cr = ENC_CODERANGE_7BIT;
2437 else {
2438 r = rb_enc_precise_mbclen(fptr->rbuf+fptr->rbuf_off, fptr->rbuf+fptr->rbuf_off+fptr->rbuf_len, enc);
2439 if (MBCLEN_CHARFOUND_P(r) &&
2440 (n = MBCLEN_CHARFOUND_LEN(r)) <= fptr->rbuf_len) {
2441 str = rb_str_new(fptr->rbuf+fptr->rbuf_off, n);
2442 fptr->rbuf_off += n;
2443 fptr->rbuf_len -= n;
2444 cr = ENC_CODERANGE_VALID;
2446 else if (MBCLEN_NEEDMORE_P(r)) {
2447 str = rb_str_new(fptr->rbuf+fptr->rbuf_off, fptr->rbuf_len);
2448 fptr->rbuf_len = 0;
2449 getc_needmore:
2450 if (io_fillbuf(fptr) != -1) {
2451 rb_str_cat(str, fptr->rbuf+fptr->rbuf_off, 1);
2452 fptr->rbuf_off++;
2453 fptr->rbuf_len--;
2454 r = rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_PTR(str)+RSTRING_LEN(str), enc);
2455 if (MBCLEN_NEEDMORE_P(r)) {
2456 goto getc_needmore;
2458 else if (MBCLEN_CHARFOUND_P(r)) {
2459 cr = ENC_CODERANGE_VALID;
2463 else {
2464 str = rb_str_new(fptr->rbuf+fptr->rbuf_off, 1);
2465 fptr->rbuf_off++;
2466 fptr->rbuf_len--;
2469 if (!cr) cr = ENC_CODERANGE_BROKEN;
2470 str = io_enc_str(str, fptr);
2471 if (!fptr->enc2) {
2472 ENC_CODERANGE_SET(str, cr);
2474 return str;
2478 * call-seq:
2479 * ios.each_char {|c| block } => ios
2481 * Calls the given block once for each character in <em>ios</em>,
2482 * passing the character as an argument. The stream must be opened for
2483 * reading or an <code>IOError</code> will be raised.
2485 * f = File.new("testfile")
2486 * f.each_char {|c| print c, ' ' } #=> #<File:testfile>
2489 static VALUE
2490 rb_io_each_char(VALUE io)
2492 rb_io_t *fptr;
2493 rb_encoding *enc;
2494 VALUE c;
2496 RETURN_ENUMERATOR(io, 0, 0);
2497 GetOpenFile(io, fptr);
2498 rb_io_check_readable(fptr);
2500 enc = io_input_encoding(fptr);
2501 READ_CHECK(fptr);
2502 while (!NIL_P(c = io_getc(fptr, enc))) {
2503 rb_yield(c);
2505 return io;
2511 * call-seq:
2512 * ios.lines(sep=$/) => anEnumerator
2513 * ios.lines(limit) => anEnumerator
2514 * ios.lines(sep, limit) => anEnumerator
2516 * Returns an enumerator that gives each line in <em>ios</em>.
2517 * The stream must be opened for reading or an <code>IOError</code>
2518 * will be raised.
2520 * f = File.new("testfile")
2521 * f.lines.to_a #=> ["foo\n", "bar\n"]
2522 * f.rewind
2523 * f.lines.sort #=> ["bar\n", "foo\n"]
2526 static VALUE
2527 rb_io_lines(int argc, VALUE *argv, VALUE io)
2529 return rb_enumeratorize(io, ID2SYM(rb_intern("each_line")), argc, argv);
2533 * call-seq:
2534 * ios.bytes => anEnumerator
2536 * Returns an enumerator that gives each byte (0..255) in <em>ios</em>.
2537 * The stream must be opened for reading or an <code>IOError</code>
2538 * will be raised.
2540 * f = File.new("testfile")
2541 * f.bytes.to_a #=> [104, 101, 108, 108, 111]
2542 * f.rewind
2543 * f.bytes.sort #=> [101, 104, 108, 108, 111]
2546 static VALUE
2547 rb_io_bytes(VALUE io)
2549 return rb_enumeratorize(io, ID2SYM(rb_intern("each_byte")), 0, 0);
2553 * call-seq:
2554 * ios.chars => anEnumerator
2556 * Returns an enumerator that gives each character in <em>ios</em>.
2557 * The stream must be opened for reading or an <code>IOError</code>
2558 * will be raised.
2560 * f = File.new("testfile")
2561 * f.chars.to_a #=> ["h", "e", "l", "l", "o"]
2562 * f.rewind
2563 * f.chars.sort #=> ["e", "h", "l", "l", "o"]
2566 static VALUE
2567 rb_io_chars(VALUE io)
2569 return rb_enumeratorize(io, ID2SYM(rb_intern("each_char")), 0, 0);
2573 * call-seq:
2574 * ios.getc => fixnum or nil
2576 * Reads a one-character string from <em>ios</em>. Returns
2577 * <code>nil</code> if called at end of file.
2579 * f = File.new("testfile")
2580 * f.getc #=> "8"
2581 * f.getc #=> "1"
2584 static VALUE
2585 rb_io_getc(VALUE io)
2587 rb_io_t *fptr;
2588 rb_encoding *enc;
2590 GetOpenFile(io, fptr);
2591 rb_io_check_readable(fptr);
2593 enc = io_input_encoding(fptr);
2594 READ_CHECK(fptr);
2595 return io_getc(fptr, enc);
2598 rb_getc(FILE *f)
2600 int c;
2602 rb_read_check(f);
2603 TRAP_BEG;
2604 c = getc(f);
2605 TRAP_END;
2607 return c;
2611 * call-seq:
2612 * ios.readchar => string
2614 * Reads a one-character string from <em>ios</em>. Raises an
2615 * <code>EOFError</code> on end of file.
2617 * f = File.new("testfile")
2618 * f.readchar #=> "8"
2619 * f.readchar #=> "1"
2622 static VALUE
2623 rb_io_readchar(VALUE io)
2625 VALUE c = rb_io_getc(io);
2627 if (NIL_P(c)) {
2628 rb_eof_error();
2630 return c;
2634 * call-seq:
2635 * ios.getbyte => fixnum or nil
2637 * Gets the next 8-bit byte (0..255) from <em>ios</em>. Returns
2638 * <code>nil</code> if called at end of file.
2640 * f = File.new("testfile")
2641 * f.getbyte #=> 84
2642 * f.getbyte #=> 104
2645 VALUE
2646 rb_io_getbyte(VALUE io)
2648 rb_io_t *fptr;
2649 int c;
2651 GetOpenFile(io, fptr);
2652 rb_io_check_readable(fptr);
2653 READ_CHECK(fptr);
2654 if (fptr->fd == 0 && (fptr->mode & FMODE_TTY) && TYPE(rb_stdout) == T_FILE) {
2655 rb_io_t *ofp;
2656 GetOpenFile(rb_stdout, ofp);
2657 if (ofp->mode & FMODE_TTY) {
2658 rb_io_flush(rb_stdout);
2661 if (io_fillbuf(fptr) < 0) {
2662 return Qnil;
2664 fptr->rbuf_off++;
2665 fptr->rbuf_len--;
2666 c = (unsigned char)fptr->rbuf[fptr->rbuf_off-1];
2667 return INT2FIX(c & 0xff);
2671 * call-seq:
2672 * ios.readbyte => fixnum
2674 * Reads a character as with <code>IO#getc</code>, but raises an
2675 * <code>EOFError</code> on end of file.
2678 static VALUE
2679 rb_io_readbyte(VALUE io)
2681 VALUE c = rb_io_getbyte(io);
2683 if (NIL_P(c)) {
2684 rb_eof_error();
2686 return c;
2690 * call-seq:
2691 * ios.ungetc(string) => nil
2693 * Pushes back one character (passed as a parameter) onto <em>ios</em>,
2694 * such that a subsequent buffered read will return it. Only one character
2695 * may be pushed back before a subsequent read operation (that is,
2696 * you will be able to read only the last of several characters that have been pushed
2697 * back). Has no effect with unbuffered reads (such as <code>IO#sysread</code>).
2699 * f = File.new("testfile") #=> #<File:testfile>
2700 * c = f.getc #=> "8"
2701 * f.ungetc(c) #=> nil
2702 * f.getc #=> "8"
2705 VALUE
2706 rb_io_ungetc(VALUE io, VALUE c)
2708 rb_io_t *fptr;
2710 GetOpenFile(io, fptr);
2711 rb_io_check_readable(fptr);
2712 if (NIL_P(c)) return Qnil;
2713 if (FIXNUM_P(c)) {
2714 int cc = FIX2INT(c);
2715 rb_encoding *enc = io_read_encoding(fptr);
2716 char buf[16];
2718 c = rb_str_new(buf, rb_enc_mbcput(cc, buf, enc));
2720 else {
2721 SafeStringValue(c);
2723 io_ungetc(c, fptr);
2724 return Qnil;
2728 * call-seq:
2729 * ios.isatty => true or false
2730 * ios.tty? => true or false
2732 * Returns <code>true</code> if <em>ios</em> is associated with a
2733 * terminal device (tty), <code>false</code> otherwise.
2735 * File.new("testfile").isatty #=> false
2736 * File.new("/dev/tty").isatty #=> true
2739 static VALUE
2740 rb_io_isatty(VALUE io)
2742 rb_io_t *fptr;
2744 GetOpenFile(io, fptr);
2745 if (isatty(fptr->fd) == 0)
2746 return Qfalse;
2747 return Qtrue;
2751 * call-seq:
2752 * ios.close_on_exec? => true or false
2754 * Returns <code>true</code> if <em>ios</em> will be closed on exec.
2756 * f = open("/dev/null")
2757 * f.close_on_exec? #=> false
2758 * f.close_on_exec = true
2759 * f.close_on_exec? #=> true
2760 * f.close_on_exec = false
2761 * f.close_on_exec? #=> false
2764 static VALUE
2765 rb_io_close_on_exec_p(VALUE io)
2767 #if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
2768 rb_io_t *fptr;
2769 VALUE write_io;
2770 int fd, ret;
2772 write_io = GetWriteIO(io);
2773 if (io != write_io) {
2774 GetOpenFile(write_io, fptr);
2775 if (fptr && 0 <= (fd = fptr->fd)) {
2776 if ((ret = fcntl(fd, F_GETFD)) == -1) rb_sys_fail(fptr->path);
2777 if (!(ret & FD_CLOEXEC)) return Qfalse;
2781 GetOpenFile(io, fptr);
2782 if (fptr && 0 <= (fd = fptr->fd)) {
2783 if ((ret = fcntl(fd, F_GETFD)) == -1) rb_sys_fail(fptr->path);
2784 if (!(ret & FD_CLOEXEC)) return Qfalse;
2786 return Qtrue;
2787 #else
2788 rb_notimplement();
2789 return Qnil; /* not reached */
2790 #endif
2794 * call-seq:
2795 * ios.close_on_exec = bool => true or false
2797 * Sets a close-on-exec flag.
2799 * f = open("/dev/null")
2800 * f.close_on_exec = true
2801 * system("cat", "/proc/self/fd/#{f.fileno}") # cat: /proc/self/fd/3: No such file or directory
2802 * f.closed? #=> false
2805 static VALUE
2806 rb_io_set_close_on_exec(VALUE io, VALUE arg)
2808 #if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
2809 int flag = RTEST(arg) ? FD_CLOEXEC : 0;
2810 rb_io_t *fptr;
2811 VALUE write_io;
2812 int fd, ret;
2814 write_io = GetWriteIO(io);
2815 if (io != write_io) {
2816 GetOpenFile(write_io, fptr);
2817 if (fptr && 0 <= (fd = fptr->fd)) {
2818 if ((ret = fcntl(fptr->fd, F_GETFD)) == -1) rb_sys_fail(fptr->path);
2819 if ((ret & FD_CLOEXEC) != flag) {
2820 ret = (ret & ~FD_CLOEXEC) | flag;
2821 ret = fcntl(fd, F_SETFD, ret);
2822 if (ret == -1) rb_sys_fail(fptr->path);
2828 GetOpenFile(io, fptr);
2829 if (fptr && 0 <= (fd = fptr->fd)) {
2830 if ((ret = fcntl(fd, F_GETFD)) == -1) rb_sys_fail(fptr->path);
2831 if ((ret & FD_CLOEXEC) != flag) {
2832 ret = (ret & ~FD_CLOEXEC) | flag;
2833 ret = fcntl(fd, F_SETFD, ret);
2834 if (ret == -1) rb_sys_fail(fptr->path);
2837 #else
2838 rb_notimplement();
2839 #endif
2840 return Qnil;
2843 #define FMODE_PREP (1<<16)
2844 #define IS_PREP_STDIO(f) ((f)->mode & FMODE_PREP)
2845 #define PREP_STDIO_NAME(f) ((f)->path)
2847 static void
2848 fptr_finalize(rb_io_t *fptr, int noraise)
2850 int ebadf = 0;
2851 if (fptr->wbuf_len) {
2852 io_fflush(fptr);
2854 if (IS_PREP_STDIO(fptr) ||
2855 fptr->fd <= 2) {
2856 return;
2858 if (fptr->stdio_file) {
2859 if (fclose(fptr->stdio_file) < 0 && !noraise) {
2860 /* fptr->stdio_file is deallocated anyway */
2861 fptr->stdio_file = 0;
2862 fptr->fd = -1;
2863 rb_sys_fail(fptr->path);
2866 else if (0 <= fptr->fd) {
2867 if (close(fptr->fd) < 0 && !noraise) {
2868 if (errno != EBADF) {
2869 /* fptr->fd is still not closed */
2870 rb_sys_fail(fptr->path);
2872 else {
2873 /* fptr->fd is already closed. */
2874 ebadf = 1;
2878 fptr->fd = -1;
2879 fptr->stdio_file = 0;
2880 fptr->mode &= ~(FMODE_READABLE|FMODE_WRITABLE);
2881 if (ebadf) {
2882 rb_sys_fail(fptr->path);
2886 static void
2887 rb_io_fptr_cleanup(rb_io_t *fptr, int noraise)
2889 if (fptr->finalize) {
2890 (*fptr->finalize)(fptr, noraise);
2892 else {
2893 fptr_finalize(fptr, noraise);
2898 rb_io_fptr_finalize(rb_io_t *fptr)
2900 if (!fptr) return 0;
2901 if (fptr->refcnt <= 0 || --fptr->refcnt) return 0;
2902 if (fptr->path) {
2903 free(fptr->path);
2904 fptr->path = 0;
2906 if (0 <= fptr->fd)
2907 rb_io_fptr_cleanup(fptr, Qtrue);
2908 if (fptr->rbuf) {
2909 free(fptr->rbuf);
2910 fptr->rbuf = 0;
2912 if (fptr->wbuf) {
2913 free(fptr->wbuf);
2914 fptr->wbuf = 0;
2916 if (fptr->readconv) {
2917 rb_econv_close(fptr->readconv);
2918 fptr->readconv = NULL;
2920 if (fptr->crbuf) {
2921 free(fptr->crbuf);
2922 fptr->crbuf = NULL;
2924 free(fptr);
2925 return 1;
2928 VALUE
2929 rb_io_close(VALUE io)
2931 rb_io_t *fptr;
2932 int fd;
2933 VALUE write_io;
2934 rb_io_t *write_fptr;
2936 write_io = GetWriteIO(io);
2937 if (io != write_io) {
2938 write_fptr = RFILE(write_io)->fptr;
2939 if (write_fptr && 0 <= write_fptr->fd) {
2940 rb_io_fptr_cleanup(write_fptr, Qtrue);
2944 fptr = RFILE(io)->fptr;
2945 if (!fptr) return Qnil;
2946 if (fptr->fd < 0) return Qnil;
2948 fd = fptr->fd;
2949 rb_io_fptr_cleanup(fptr, Qfalse);
2950 rb_thread_fd_close(fd);
2952 if (fptr->pid) {
2953 rb_syswait(fptr->pid);
2954 fptr->pid = 0;
2957 return Qnil;
2961 * call-seq:
2962 * ios.close => nil
2964 * Closes <em>ios</em> and flushes any pending writes to the operating
2965 * system. The stream is unavailable for any further data operations;
2966 * an <code>IOError</code> is raised if such an attempt is made. I/O
2967 * streams are automatically closed when they are claimed by the
2968 * garbage collector.
2970 * If <em>ios</em> is opened by <code>IO.popen</code>,
2971 * <code>close</code> sets <code>$?</code>.
2974 static VALUE
2975 rb_io_close_m(VALUE io)
2977 if (rb_safe_level() >= 4 && !OBJ_UNTRUSTED(io)) {
2978 rb_raise(rb_eSecurityError, "Insecure: can't close");
2980 rb_io_check_closed(RFILE(io)->fptr);
2981 rb_io_close(io);
2982 return Qnil;
2985 static VALUE
2986 io_call_close(VALUE io)
2988 return rb_funcall(io, rb_intern("close"), 0, 0);
2991 static VALUE
2992 io_close(VALUE io)
2994 return rb_rescue(io_call_close, io, 0, 0);
2998 * call-seq:
2999 * ios.closed? => true or false
3001 * Returns <code>true</code> if <em>ios</em> is completely closed (for
3002 * duplex streams, both reader and writer), <code>false</code>
3003 * otherwise.
3005 * f = File.new("testfile")
3006 * f.close #=> nil
3007 * f.closed? #=> true
3008 * f = IO.popen("/bin/sh","r+")
3009 * f.close_write #=> nil
3010 * f.closed? #=> false
3011 * f.close_read #=> nil
3012 * f.closed? #=> true
3016 static VALUE
3017 rb_io_closed(VALUE io)
3019 rb_io_t *fptr;
3020 VALUE write_io;
3021 rb_io_t *write_fptr;
3023 write_io = GetWriteIO(io);
3024 if (io != write_io) {
3025 write_fptr = RFILE(write_io)->fptr;
3026 if (write_fptr && 0 <= write_fptr->fd) {
3027 return Qfalse;
3031 fptr = RFILE(io)->fptr;
3032 rb_io_check_initialized(fptr);
3033 return 0 <= fptr->fd ? Qfalse : Qtrue;
3037 * call-seq:
3038 * ios.close_read => nil
3040 * Closes the read end of a duplex I/O stream (i.e., one that contains
3041 * both a read and a write stream, such as a pipe). Will raise an
3042 * <code>IOError</code> if the stream is not duplexed.
3044 * f = IO.popen("/bin/sh","r+")
3045 * f.close_read
3046 * f.readlines
3048 * <em>produces:</em>
3050 * prog.rb:3:in `readlines': not opened for reading (IOError)
3051 * from prog.rb:3
3054 static VALUE
3055 rb_io_close_read(VALUE io)
3057 rb_io_t *fptr;
3058 VALUE write_io;
3060 if (rb_safe_level() >= 4 && !OBJ_UNTRUSTED(io)) {
3061 rb_raise(rb_eSecurityError, "Insecure: can't close");
3063 GetOpenFile(io, fptr);
3064 if (is_socket(fptr->fd, fptr->path)) {
3065 #ifndef SHUT_RD
3066 # define SHUT_RD 0
3067 #endif
3068 if (shutdown(fptr->fd, SHUT_RD) < 0)
3069 rb_sys_fail(fptr->path);
3070 fptr->mode &= ~FMODE_READABLE;
3071 if (!(fptr->mode & FMODE_WRITABLE))
3072 return rb_io_close(io);
3073 return Qnil;
3076 write_io = GetWriteIO(io);
3077 if (io != write_io) {
3078 rb_io_t *wfptr;
3079 fptr_finalize(fptr, Qfalse);
3080 GetOpenFile(write_io, wfptr);
3081 if (fptr->refcnt < LONG_MAX) {
3082 wfptr->refcnt++;
3083 RFILE(io)->fptr = wfptr;
3084 rb_io_fptr_finalize(fptr);
3086 return Qnil;
3089 if (fptr->mode & FMODE_WRITABLE) {
3090 rb_raise(rb_eIOError, "closing non-duplex IO for reading");
3092 return rb_io_close(io);
3096 * call-seq:
3097 * ios.close_write => nil
3099 * Closes the write end of a duplex I/O stream (i.e., one that contains
3100 * both a read and a write stream, such as a pipe). Will raise an
3101 * <code>IOError</code> if the stream is not duplexed.
3103 * f = IO.popen("/bin/sh","r+")
3104 * f.close_write
3105 * f.print "nowhere"
3107 * <em>produces:</em>
3109 * prog.rb:3:in `write': not opened for writing (IOError)
3110 * from prog.rb:3:in `print'
3111 * from prog.rb:3
3114 static VALUE
3115 rb_io_close_write(VALUE io)
3117 rb_io_t *fptr;
3118 VALUE write_io;
3120 if (rb_safe_level() >= 4 && !OBJ_UNTRUSTED(io)) {
3121 rb_raise(rb_eSecurityError, "Insecure: can't close");
3123 write_io = GetWriteIO(io);
3124 GetOpenFile(write_io, fptr);
3125 if (is_socket(fptr->fd, fptr->path)) {
3126 #ifndef SHUT_WR
3127 # define SHUT_WR 1
3128 #endif
3129 if (shutdown(fptr->fd, SHUT_WR) < 0)
3130 rb_sys_fail(fptr->path);
3131 fptr->mode &= ~FMODE_WRITABLE;
3132 if (!(fptr->mode & FMODE_READABLE))
3133 return rb_io_close(write_io);
3134 return Qnil;
3137 if (fptr->mode & FMODE_READABLE) {
3138 rb_raise(rb_eIOError, "closing non-duplex IO for writing");
3141 rb_io_close(write_io);
3142 if (io != write_io) {
3143 GetOpenFile(io, fptr);
3144 fptr->tied_io_for_writing = 0;
3145 fptr->mode &= ~FMODE_DUPLEX;
3147 return Qnil;
3151 * call-seq:
3152 * ios.sysseek(offset, whence=SEEK_SET) => integer
3154 * Seeks to a given <i>offset</i> in the stream according to the value
3155 * of <i>whence</i> (see <code>IO#seek</code> for values of
3156 * <i>whence</i>). Returns the new offset into the file.
3158 * f = File.new("testfile")
3159 * f.sysseek(-13, IO::SEEK_END) #=> 53
3160 * f.sysread(10) #=> "And so on."
3163 static VALUE
3164 rb_io_sysseek(int argc, VALUE *argv, VALUE io)
3166 VALUE offset, ptrname;
3167 int whence = SEEK_SET;
3168 rb_io_t *fptr;
3169 off_t pos;
3171 if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) {
3172 whence = NUM2INT(ptrname);
3174 pos = NUM2OFFT(offset);
3175 GetOpenFile(io, fptr);
3176 if ((fptr->mode & FMODE_READABLE) && READ_DATA_BUFFERED(fptr)) {
3177 rb_raise(rb_eIOError, "sysseek for buffered IO");
3179 if ((fptr->mode & FMODE_WRITABLE) && fptr->wbuf_len) {
3180 rb_warn("sysseek for buffered IO");
3182 pos = lseek(fptr->fd, pos, whence);
3183 if (pos == -1) rb_sys_fail(fptr->path);
3185 return OFFT2NUM(pos);
3189 * call-seq:
3190 * ios.syswrite(string) => integer
3192 * Writes the given string to <em>ios</em> using a low-level write.
3193 * Returns the number of bytes written. Do not mix with other methods
3194 * that write to <em>ios</em> or you may get unpredictable results.
3195 * Raises <code>SystemCallError</code> on error.
3197 * f = File.new("out", "w")
3198 * f.syswrite("ABCDEF") #=> 6
3201 static VALUE
3202 rb_io_syswrite(VALUE io, VALUE str)
3204 rb_io_t *fptr;
3205 long n;
3207 rb_secure(4);
3208 if (TYPE(str) != T_STRING)
3209 str = rb_obj_as_string(str);
3211 io = GetWriteIO(io);
3212 GetOpenFile(io, fptr);
3213 rb_io_check_writable(fptr);
3215 if (fptr->wbuf_len) {
3216 rb_warn("syswrite for buffered IO");
3218 if (!rb_thread_fd_writable(fptr->fd)) {
3219 rb_io_check_closed(fptr);
3221 TRAP_BEG;
3222 n = write(fptr->fd, RSTRING_PTR(str), RSTRING_LEN(str));
3223 TRAP_END;
3225 if (n == -1) rb_sys_fail(fptr->path);
3227 return LONG2FIX(n);
3231 * call-seq:
3232 * ios.sysread(integer[, outbuf]) => string
3234 * Reads <i>integer</i> bytes from <em>ios</em> using a low-level
3235 * read and returns them as a string. Do not mix with other methods
3236 * that read from <em>ios</em> or you may get unpredictable results.
3237 * If the optional <i>outbuf</i> argument is present, it must reference
3238 * a String, which will receive the data.
3239 * Raises <code>SystemCallError</code> on error and
3240 * <code>EOFError</code> at end of file.
3242 * f = File.new("testfile")
3243 * f.sysread(16) #=> "This is line one"
3246 static VALUE
3247 rb_io_sysread(int argc, VALUE *argv, VALUE io)
3249 VALUE len, str;
3250 rb_io_t *fptr;
3251 long n, ilen;
3253 rb_scan_args(argc, argv, "11", &len, &str);
3254 ilen = NUM2LONG(len);
3256 if (NIL_P(str)) {
3257 str = rb_str_new(0, ilen);
3259 else {
3260 StringValue(str);
3261 rb_str_modify(str);
3262 rb_str_resize(str, ilen);
3264 if (ilen == 0) return str;
3266 GetOpenFile(io, fptr);
3267 rb_io_check_readable(fptr);
3269 if (READ_DATA_BUFFERED(fptr)) {
3270 rb_raise(rb_eIOError, "sysread for buffered IO");
3273 n = fptr->fd;
3274 rb_thread_wait_fd(fptr->fd);
3275 rb_io_check_closed(fptr);
3276 if (RSTRING_LEN(str) != ilen) {
3277 rb_raise(rb_eRuntimeError, "buffer string modified");
3280 n = rb_read_internal(fptr->fd, RSTRING_PTR(str), ilen);
3282 if (n == -1) {
3283 rb_sys_fail(fptr->path);
3285 rb_str_set_len(str, n);
3286 if (n == 0 && ilen > 0) {
3287 rb_eof_error();
3289 rb_str_resize(str, n);
3290 OBJ_TAINT(str);
3292 return str;
3295 VALUE
3296 rb_io_binmode(VALUE io)
3298 rb_io_t *fptr;
3300 GetOpenFile(io, fptr);
3301 #if defined(_WIN32) || defined(DJGPP) || defined(__CYGWIN__) || defined(__human68k__) || defined(__EMX__)
3302 if (!(fptr->mode & FMODE_BINMODE) && READ_DATA_BUFFERED(fptr)) {
3303 rb_raise(rb_eIOError, "buffer already filled with text-mode content");
3305 if (0 <= fptr->fd && setmode(fptr->fd, O_BINARY) == -1)
3306 rb_sys_fail(fptr->path);
3307 #endif
3308 fptr->mode |= FMODE_BINMODE;
3309 return io;
3313 * call-seq:
3314 * ios.binmode => ios
3316 * Puts <em>ios</em> into binary mode. This is useful only in
3317 * MS-DOS/Windows environments. Once a stream is in binary mode, it
3318 * cannot be reset to nonbinary mode.
3321 static VALUE
3322 rb_io_binmode_m(VALUE io)
3324 #if defined(_WIN32) || defined(DJGPP) || defined(__CYGWIN__) || defined(__human68k__) || defined(__EMX__)
3325 VALUE write_io;
3326 #endif
3328 rb_io_binmode(io);
3330 #if defined(_WIN32) || defined(DJGPP) || defined(__CYGWIN__) || defined(__human68k__) || defined(__EMX__)
3331 write_io = GetWriteIO(io);
3332 if (write_io != io)
3333 rb_io_binmode(write_io);
3334 #endif
3335 return io;
3339 * call-seq:
3340 * ios.binmode? => true or false
3342 * Returns <code>true</code> if <em>ios</em> is binmode.
3344 static VALUE
3345 rb_io_binmode_p(VALUE io)
3347 rb_io_t *fptr;
3348 GetOpenFile(io, fptr);
3349 return fptr->mode & FMODE_BINMODE ? Qtrue : Qfalse;
3352 static const char*
3353 rb_io_flags_mode(int flags)
3355 #ifdef O_BINARY
3356 # define MODE_BINMODE(a,b) ((flags & FMODE_BINMODE) ? (b) : (a))
3357 #else
3358 # define MODE_BINMODE(a,b) (a)
3359 #endif
3360 if (flags & FMODE_APPEND) {
3361 if ((flags & FMODE_READWRITE) == FMODE_READWRITE) {
3362 return MODE_BINMODE("a+", "ab+");
3364 return MODE_BINMODE("a", "ab");
3366 switch (flags & FMODE_READWRITE) {
3367 case FMODE_READABLE:
3368 return MODE_BINMODE("r", "rb");
3369 case FMODE_WRITABLE:
3370 return MODE_BINMODE("w", "wb");
3371 case FMODE_READWRITE:
3372 if (flags & FMODE_CREATE) {
3373 return MODE_BINMODE("w+", "wb+");
3375 return MODE_BINMODE("r+", "rb+");
3377 rb_raise(rb_eArgError, "invalid access modenum %o", flags);
3378 return NULL; /* not reached */
3382 rb_io_mode_flags(const char *mode)
3384 int flags = 0;
3385 const char *m = mode;
3387 switch (*m++) {
3388 case 'r':
3389 flags |= FMODE_READABLE;
3390 break;
3391 case 'w':
3392 flags |= FMODE_WRITABLE | FMODE_CREATE;
3393 break;
3394 case 'a':
3395 flags |= FMODE_WRITABLE | FMODE_APPEND | FMODE_CREATE;
3396 break;
3397 default:
3398 error:
3399 rb_raise(rb_eArgError, "invalid access mode %s", mode);
3402 while (*m) {
3403 switch (*m++) {
3404 case 'b':
3405 flags |= FMODE_BINMODE;
3406 break;
3407 case '+':
3408 flags |= FMODE_READWRITE;
3409 break;
3410 default:
3411 goto error;
3412 case ':':
3413 return flags;
3417 return flags;
3421 rb_io_modenum_flags(int mode)
3423 int flags = 0;
3425 switch (mode & (O_RDONLY|O_WRONLY|O_RDWR)) {
3426 case O_RDONLY:
3427 flags = FMODE_READABLE;
3428 break;
3429 case O_WRONLY:
3430 flags = FMODE_WRITABLE;
3431 break;
3432 case O_RDWR:
3433 flags = FMODE_READWRITE;
3434 break;
3437 if (mode & O_APPEND) {
3438 flags |= FMODE_APPEND;
3440 if (mode & O_CREAT) {
3441 flags |= FMODE_CREATE;
3443 #ifdef O_BINARY
3444 if (mode & O_BINARY) {
3445 flags |= FMODE_BINMODE;
3447 #endif
3449 return flags;
3453 rb_io_mode_modenum(const char *mode)
3455 int flags = 0;
3456 const char *m = mode;
3458 switch (*m++) {
3459 case 'r':
3460 flags |= O_RDONLY;
3461 break;
3462 case 'w':
3463 flags |= O_WRONLY | O_CREAT | O_TRUNC;
3464 break;
3465 case 'a':
3466 flags |= O_WRONLY | O_CREAT | O_APPEND;
3467 break;
3468 default:
3469 error:
3470 rb_raise(rb_eArgError, "invalid access mode %s", mode);
3473 while (*m) {
3474 switch (*m++) {
3475 case 'b':
3476 #ifdef O_BINARY
3477 flags |= O_BINARY;
3478 #endif
3479 break;
3480 case '+':
3481 flags = (flags & ~O_ACCMODE) | O_RDWR;
3482 break;
3483 default:
3484 goto error;
3485 case ':':
3486 return flags;
3490 return flags;
3493 #define MODENUM_MAX 4
3495 static const char*
3496 rb_io_modenum_mode(int flags)
3498 #ifdef O_BINARY
3499 # define MODE_BINARY(a,b) ((flags & O_BINARY) ? (b) : (a))
3500 #else
3501 # define MODE_BINARY(a,b) (a)
3502 #endif
3503 if (flags & O_APPEND) {
3504 if ((flags & O_RDWR) == O_RDWR) {
3505 return MODE_BINARY("a+", "ab+");
3507 return MODE_BINARY("a", "ab");
3509 switch (flags & (O_RDONLY|O_WRONLY|O_RDWR)) {
3510 case O_RDONLY:
3511 return MODE_BINARY("r", "rb");
3512 case O_WRONLY:
3513 return MODE_BINARY("w", "wb");
3514 case O_RDWR:
3515 return MODE_BINARY("r+", "rb+");
3517 rb_raise(rb_eArgError, "invalid access modenum %o", flags);
3518 return NULL; /* not reached */
3521 static void
3522 mode_enc(rb_io_t *fptr, const char *estr)
3524 const char *p0, *p1;
3525 char *enc2name;
3526 int idx, idx2;
3528 /* parse estr as "enc" or "enc2:enc" */
3530 fptr->enc = 0;
3531 fptr->enc2 = 0;
3533 p0 = strrchr(estr, ':');
3534 if (!p0) p1 = estr;
3535 else p1 = p0 + 1;
3536 idx = rb_enc_find_index(p1);
3537 if (idx >= 0) {
3538 fptr->enc = rb_enc_from_index(idx);
3540 else {
3541 rb_warn("Unsupported encoding %s ignored", p1);
3544 if (fptr->enc && p0) {
3545 int n = p0 - estr;
3546 if (n > ENCODING_MAXNAMELEN) {
3547 idx2 = -1;
3549 else {
3550 enc2name = ALLOCA_N(char, n+1);
3551 memcpy(enc2name, estr, n);
3552 enc2name[n] = '\0';
3553 estr = enc2name;
3554 idx2 = rb_enc_find_index(enc2name);
3556 if (idx2 < 0) {
3557 rb_warn("Unsupported encoding %.*s ignored", n, estr);
3559 else if (idx2 == idx) {
3560 rb_warn("Ignoring internal encoding %.*s: it is identical to external encoding %s",
3561 n, estr, p1);
3563 else {
3564 fptr->enc2 = rb_enc_from_index(idx2);
3569 void
3570 rb_io_mode_enc(rb_io_t *fptr, const char *mode)
3572 const char *p = strchr(mode, ':');
3573 if (p) {
3574 mode_enc(fptr, p+1);
3578 struct sysopen_struct {
3579 char *fname;
3580 int flag;
3581 unsigned int mode;
3584 static VALUE
3585 sysopen_func(void *ptr)
3587 struct sysopen_struct *data = ptr;
3588 return (VALUE)open(data->fname, data->flag, data->mode);
3591 static int
3592 rb_sysopen_internal(char *fname, int flags, unsigned int mode)
3594 struct sysopen_struct data;
3595 data.fname = fname;
3596 data.flag = flags;
3597 data.mode = mode;
3598 return (int)rb_thread_blocking_region(sysopen_func, &data, RB_UBF_DFL, 0);
3601 static int
3602 rb_sysopen(char *fname, int flags, unsigned int mode)
3604 int fd;
3606 fd = rb_sysopen_internal(fname, flags, mode);
3607 if (fd < 0) {
3608 if (errno == EMFILE || errno == ENFILE) {
3609 rb_gc();
3610 fd = rb_sysopen_internal(fname, flags, mode);
3612 if (fd < 0) {
3613 rb_sys_fail(fname);
3616 UPDATE_MAXFD(fd);
3617 return fd;
3620 FILE *
3621 rb_fopen(const char *fname, const char *mode)
3623 FILE *file;
3625 file = fopen(fname, mode);
3626 if (!file) {
3627 if (errno == EMFILE || errno == ENFILE) {
3628 rb_gc();
3629 file = fopen(fname, mode);
3631 if (!file) {
3632 rb_sys_fail(fname);
3635 #ifdef USE_SETVBUF
3636 if (setvbuf(file, NULL, _IOFBF, 0) != 0)
3637 rb_warn("setvbuf() can't be honoured for %s", fname);
3638 #endif
3639 #ifdef __human68k__
3640 setmode(fileno(file), O_TEXT);
3641 #endif
3642 return file;
3645 FILE *
3646 rb_fdopen(int fd, const char *mode)
3648 FILE *file;
3650 #if defined(sun)
3651 errno = 0;
3652 #endif
3653 file = fdopen(fd, mode);
3654 if (!file) {
3655 if (
3656 #if defined(sun)
3657 errno == 0 ||
3658 #endif
3659 errno == EMFILE || errno == ENFILE) {
3660 rb_gc();
3661 #if defined(sun)
3662 errno = 0;
3663 #endif
3664 file = fdopen(fd, mode);
3666 if (!file) {
3667 #ifdef _WIN32
3668 if (errno == 0) errno = EINVAL;
3669 #elif defined(sun)
3670 if (errno == 0) errno = EMFILE;
3671 #endif
3672 rb_sys_fail(0);
3676 /* xxx: should be _IONBF? A buffer in FILE may have trouble. */
3677 #ifdef USE_SETVBUF
3678 if (setvbuf(file, NULL, _IOFBF, 0) != 0)
3679 rb_warn("setvbuf() can't be honoured (fd=%d)", fd);
3680 #endif
3681 return file;
3684 static void
3685 io_check_tty(rb_io_t *fptr)
3687 if (isatty(fptr->fd))
3688 fptr->mode |= FMODE_TTY|FMODE_DUPLEX;
3691 static VALUE
3692 rb_file_open_internal(VALUE io, const char *fname, const char *mode)
3694 rb_io_t *fptr;
3696 MakeOpenFile(io, fptr);
3697 fptr->mode = rb_io_mode_flags(mode);
3698 rb_io_mode_enc(fptr, mode);
3699 fptr->path = strdup(fname);
3700 fptr->fd = rb_sysopen(fptr->path, rb_io_mode_modenum(rb_io_flags_mode(fptr->mode)), 0666);
3701 io_check_tty(fptr);
3703 return io;
3706 VALUE
3707 rb_file_open(const char *fname, const char *mode)
3709 return rb_file_open_internal(io_alloc(rb_cFile), fname, mode);
3712 static VALUE
3713 rb_file_sysopen_internal(VALUE io, const char *fname, int flags, int mode)
3715 rb_io_t *fptr;
3717 MakeOpenFile(io, fptr);
3719 fptr->path = strdup(fname);
3720 fptr->mode = rb_io_modenum_flags(flags);
3721 fptr->fd = rb_sysopen(fptr->path, flags, mode);
3722 io_check_tty(fptr);
3724 return io;
3727 VALUE
3728 rb_file_sysopen(const char *fname, int flags, int mode)
3730 return rb_file_sysopen_internal(io_alloc(rb_cFile), fname, flags, mode);
3733 #if defined(__CYGWIN__) || !defined(HAVE_FORK)
3734 static struct pipe_list {
3735 rb_io_t *fptr;
3736 struct pipe_list *next;
3737 } *pipe_list;
3739 static void
3740 pipe_add_fptr(rb_io_t *fptr)
3742 struct pipe_list *list;
3744 list = ALLOC(struct pipe_list);
3745 list->fptr = fptr;
3746 list->next = pipe_list;
3747 pipe_list = list;
3750 static void
3751 pipe_del_fptr(rb_io_t *fptr)
3753 struct pipe_list *list = pipe_list;
3754 struct pipe_list *tmp;
3756 if (list->fptr == fptr) {
3757 pipe_list = list->next;
3758 free(list);
3759 return;
3762 while (list->next) {
3763 if (list->next->fptr == fptr) {
3764 tmp = list->next;
3765 list->next = list->next->next;
3766 free(tmp);
3767 return;
3769 list = list->next;
3773 static void
3774 pipe_atexit(void)
3776 struct pipe_list *list = pipe_list;
3777 struct pipe_list *tmp;
3779 while (list) {
3780 tmp = list->next;
3781 rb_io_fptr_finalize(list->fptr);
3782 list = tmp;
3786 static void
3787 pipe_finalize(rb_io_t *fptr, int noraise)
3789 #if !defined(HAVE_FORK) && !defined(_WIN32)
3790 int status;
3791 if (fptr->stdio_file) {
3792 status = pclose(fptr->stdio_file);
3794 fptr->fd = -1;
3795 fptr->stdio_file = 0;
3796 #if defined DJGPP
3797 status <<= 8;
3798 #endif
3799 rb_last_status_set(status, fptr->pid);
3800 #else
3801 fptr_finalize(fptr, noraise);
3802 #endif
3803 pipe_del_fptr(fptr);
3805 #endif
3807 void
3808 rb_io_synchronized(rb_io_t *fptr)
3810 rb_io_check_initialized(fptr);
3811 fptr->mode |= FMODE_SYNC;
3814 void
3815 rb_io_unbuffered(rb_io_t *fptr)
3817 rb_io_synchronized(fptr);
3821 rb_pipe(int *pipes)
3823 int ret;
3824 ret = pipe(pipes);
3825 if (ret == -1) {
3826 if (errno == EMFILE || errno == ENFILE) {
3827 rb_gc();
3828 ret = pipe(pipes);
3831 if (ret == 0) {
3832 UPDATE_MAXFD(pipes[0]);
3833 UPDATE_MAXFD(pipes[1]);
3835 return ret;
3838 #ifdef HAVE_FORK
3839 struct popen_arg {
3840 struct rb_exec_arg *execp;
3841 int modef;
3842 int pair[2];
3843 int write_pair[2];
3846 static void
3847 popen_redirect(struct popen_arg *p)
3849 if ((p->modef & FMODE_READABLE) && (p->modef & FMODE_WRITABLE)) {
3850 close(p->write_pair[1]);
3851 if (p->write_pair[0] != 0) {
3852 dup2(p->write_pair[0], 0);
3853 close(p->write_pair[0]);
3855 close(p->pair[0]);
3856 if (p->pair[1] != 1) {
3857 dup2(p->pair[1], 1);
3858 close(p->pair[1]);
3861 else if (p->modef & FMODE_READABLE) {
3862 close(p->pair[0]);
3863 if (p->pair[1] != 1) {
3864 dup2(p->pair[1], 1);
3865 close(p->pair[1]);
3868 else {
3869 close(p->pair[1]);
3870 if (p->pair[0] != 0) {
3871 dup2(p->pair[0], 0);
3872 close(p->pair[0]);
3877 void
3878 rb_close_before_exec(int lowfd, int maxhint, VALUE noclose_fds)
3880 int fd, ret;
3881 int max = max_file_descriptor;
3882 if (max < maxhint)
3883 max = maxhint;
3884 for (fd = lowfd; fd <= max; fd++) {
3885 if (!NIL_P(noclose_fds) &&
3886 RTEST(rb_hash_lookup(noclose_fds, INT2FIX(fd))))
3887 continue;
3888 #ifdef FD_CLOEXEC
3889 ret = fcntl(fd, F_GETFD);
3890 if (ret != -1 && !(ret & FD_CLOEXEC)) {
3891 fcntl(fd, F_SETFD, ret|FD_CLOEXEC);
3893 #else
3894 close(fd);
3895 #endif
3899 static int
3900 popen_exec(void *pp)
3902 struct popen_arg *p = (struct popen_arg*)pp;
3904 rb_thread_atfork_before_exec();
3905 return rb_exec(p->execp);
3907 #endif
3909 static VALUE
3910 pipe_open(struct rb_exec_arg *eargp, VALUE prog, const char *mode)
3912 int modef = rb_io_mode_flags(mode);
3913 int pid = 0;
3914 rb_io_t *fptr;
3915 VALUE port;
3916 rb_io_t *write_fptr;
3917 VALUE write_port;
3918 #if defined(HAVE_FORK)
3919 int status;
3920 struct popen_arg arg;
3921 #elif defined(_WIN32)
3922 int openmode = rb_io_mode_modenum(mode);
3923 const char *exename = NULL;
3924 volatile VALUE cmdbuf;
3925 struct rb_exec_arg sarg;
3926 #endif
3927 FILE *fp = 0;
3928 int fd = -1;
3929 int write_fd = -1;
3930 const char *cmd = 0;
3931 int argc;
3932 VALUE *argv;
3934 if (prog)
3935 cmd = StringValueCStr(prog);
3937 if (!eargp) {
3938 /* fork : IO.popen("-") */
3939 argc = 0;
3940 argv = 0;
3942 else if (eargp->argc) {
3943 /* no shell : IO.popen([prog, arg0], arg1, ...) */
3944 argc = eargp->argc;
3945 argv = eargp->argv;
3947 else {
3948 /* with shell : IO.popen(prog) */
3949 argc = 0;
3950 argv = 0;
3953 #if defined(HAVE_FORK)
3954 arg.execp = eargp;
3955 arg.modef = modef;
3956 arg.pair[0] = arg.pair[1] = -1;
3957 arg.write_pair[0] = arg.write_pair[1] = -1;
3958 switch (modef & (FMODE_READABLE|FMODE_WRITABLE)) {
3959 case FMODE_READABLE|FMODE_WRITABLE:
3960 if (rb_pipe(arg.write_pair) < 0)
3961 rb_sys_fail(cmd);
3962 if (rb_pipe(arg.pair) < 0) {
3963 int e = errno;
3964 close(arg.write_pair[0]);
3965 close(arg.write_pair[1]);
3966 errno = e;
3967 rb_sys_fail(cmd);
3969 if (eargp) {
3970 rb_exec_arg_addopt(eargp, INT2FIX(0), INT2FIX(arg.write_pair[0]));
3971 rb_exec_arg_addopt(eargp, INT2FIX(1), INT2FIX(arg.pair[1]));
3973 break;
3974 case FMODE_READABLE:
3975 if (rb_pipe(arg.pair) < 0)
3976 rb_sys_fail(cmd);
3977 if (eargp)
3978 rb_exec_arg_addopt(eargp, INT2FIX(1), INT2FIX(arg.pair[1]));
3979 break;
3980 case FMODE_WRITABLE:
3981 if (rb_pipe(arg.pair) < 0)
3982 rb_sys_fail(cmd);
3983 if (eargp)
3984 rb_exec_arg_addopt(eargp, INT2FIX(0), INT2FIX(arg.pair[0]));
3985 break;
3986 default:
3987 rb_sys_fail(cmd);
3989 if (eargp) {
3990 rb_exec_arg_fixup(arg.execp);
3991 pid = rb_fork(&status, popen_exec, &arg, arg.execp->redirect_fds);
3993 else {
3994 fflush(stdin); /* is it really needed? */
3995 rb_io_flush(rb_stdout);
3996 rb_io_flush(rb_stderr);
3997 pid = rb_fork(&status, 0, 0, Qnil);
3998 if (pid == 0) { /* child */
3999 popen_redirect(&arg);
4000 rb_io_synchronized(RFILE(orig_stdout)->fptr);
4001 rb_io_synchronized(RFILE(orig_stderr)->fptr);
4002 return Qnil;
4006 /* parent */
4007 if (pid == -1) {
4008 int e = errno;
4009 close(arg.pair[0]);
4010 close(arg.pair[1]);
4011 if ((modef & (FMODE_READABLE|FMODE_WRITABLE)) == (FMODE_READABLE|FMODE_WRITABLE)) {
4012 close(arg.write_pair[0]);
4013 close(arg.write_pair[1]);
4015 errno = e;
4016 rb_sys_fail(cmd);
4018 if ((modef & FMODE_READABLE) && (modef & FMODE_WRITABLE)) {
4019 close(arg.pair[1]);
4020 fd = arg.pair[0];
4021 close(arg.write_pair[0]);
4022 write_fd = arg.write_pair[1];
4024 else if (modef & FMODE_READABLE) {
4025 close(arg.pair[1]);
4026 fd = arg.pair[0];
4028 else {
4029 close(arg.pair[0]);
4030 fd = arg.pair[1];
4032 #elif defined(_WIN32)
4033 if (argc) {
4034 volatile VALUE argbuf;
4035 char **args;
4036 int i;
4038 if (argc >= FIXNUM_MAX / sizeof(char *)) {
4039 rb_raise(rb_eArgError, "too many arguments");
4041 argbuf = rb_str_tmp_new((argc+1) * sizeof(char *));
4042 args = (void *)RSTRING_PTR(argbuf);
4043 for (i = 0; i < argc; ++i) {
4044 args[i] = StringValueCStr(argv[i]);
4046 args[i] = NULL;
4047 exename = cmd;
4048 cmdbuf = rb_str_tmp_new(rb_w32_argv_size(args));
4049 cmd = rb_w32_join_argv(RSTRING_PTR(cmdbuf), args);
4050 rb_str_resize(argbuf, 0);
4052 if (eargp) {
4053 rb_exec_arg_fixup(eargp);
4054 rb_run_exec_options(eargp, &sarg);
4056 while ((pid = rb_w32_pipe_exec(cmd, exename, openmode, &fd, &write_fd)) == -1) {
4057 /* exec failed */
4058 switch (errno) {
4059 case EAGAIN:
4060 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
4061 case EWOULDBLOCK:
4062 #endif
4063 rb_thread_sleep(1);
4064 break;
4065 default:
4066 if (eargp)
4067 rb_run_exec_options(&sarg, NULL);
4068 rb_sys_fail(cmd);
4069 break;
4072 if (eargp)
4073 rb_run_exec_options(&sarg, NULL);
4074 #else
4075 if (argc) {
4076 prog = rb_ary_join(rb_ary_new4(argc, argv), rb_str_new2(" "));
4077 cmd = StringValueCStr(prog);
4079 if (eargp) {
4080 rb_exec_arg_fixup(eargp);
4081 rb_run_exec_options(eargp, &sarg);
4083 fp = popen(cmd, mode);
4084 if (eargp)
4085 rb_run_exec_options(&sarg, NULL);
4086 if (!fp) rb_sys_fail(RSTRING_PTR(prog));
4087 fd = fileno(fp);
4088 #endif
4090 port = io_alloc(rb_cIO);
4091 MakeOpenFile(port, fptr);
4092 fptr->fd = fd;
4093 fptr->stdio_file = fp;
4094 fptr->mode = modef | FMODE_SYNC|FMODE_DUPLEX;
4095 rb_io_mode_enc(fptr, mode);
4096 fptr->pid = pid;
4098 if (0 <= write_fd) {
4099 write_port = io_alloc(rb_cIO);
4100 MakeOpenFile(write_port, write_fptr);
4101 write_fptr->fd = write_fd;
4102 write_fptr->mode = (modef & ~FMODE_READABLE)| FMODE_SYNC|FMODE_DUPLEX;
4103 fptr->mode &= ~FMODE_WRITABLE;
4104 fptr->tied_io_for_writing = write_port;
4105 rb_ivar_set(port, rb_intern("@tied_io_for_writing"), write_port);
4108 #if defined (__CYGWIN__) || !defined(HAVE_FORK)
4109 fptr->finalize = pipe_finalize;
4110 pipe_add_fptr(fptr);
4111 #endif
4112 return port;
4115 static VALUE
4116 pipe_open_v(int argc, VALUE *argv, const char *mode)
4118 VALUE prog;
4119 struct rb_exec_arg earg;
4120 prog = rb_exec_arg_init(argc, argv, Qfalse, &earg);
4121 return pipe_open(&earg, prog, mode);
4124 static VALUE
4125 pipe_open_s(VALUE prog, const char *mode)
4127 const char *cmd = RSTRING_PTR(prog);
4128 int argc = 1;
4129 VALUE *argv = &prog;
4130 struct rb_exec_arg earg;
4132 if (RSTRING_LEN(prog) == 1 && cmd[0] == '-') {
4133 #if !defined(HAVE_FORK)
4134 rb_raise(rb_eNotImpError,
4135 "fork() function is unimplemented on this machine");
4136 #endif
4137 return pipe_open(0, 0, mode);
4140 rb_exec_arg_init(argc, argv, Qtrue, &earg);
4141 return pipe_open(&earg, prog, mode);
4145 * call-seq:
4146 * IO.popen(cmd, mode="r") => io
4147 * IO.popen(cmd, mode="r") {|io| block } => obj
4149 * Runs the specified command as a subprocess; the subprocess's
4150 * standard input and output will be connected to the returned
4151 * <code>IO</code> object. If _cmd_ is a +String+
4152 * ``<code>-</code>'', then a new instance of Ruby is started as the
4153 * subprocess. If <i>cmd</i> is an +Array+ of +String+, then it will
4154 * be used as the subprocess's +argv+ bypassing a shell.
4155 * The array can contains a hash at first for environments and
4156 * a hash at last for options similar to <code>spawn</code>. The default
4157 * mode for the new file object is ``r'', but <i>mode</i> may be set
4158 * to any of the modes listed in the description for class IO.
4160 * Raises exceptions which <code>IO::pipe</code> and
4161 * <code>Kernel::system</code> raise.
4163 * If a block is given, Ruby will run the command as a child connected
4164 * to Ruby with a pipe. Ruby's end of the pipe will be passed as a
4165 * parameter to the block.
4166 * At the end of block, Ruby close the pipe and sets <code>$?</code>.
4167 * In this case <code>IO::popen</code> returns
4168 * the value of the block.
4170 * If a block is given with a _cmd_ of ``<code>-</code>'',
4171 * the block will be run in two separate processes: once in the parent,
4172 * and once in a child. The parent process will be passed the pipe
4173 * object as a parameter to the block, the child version of the block
4174 * will be passed <code>nil</code>, and the child's standard in and
4175 * standard out will be connected to the parent through the pipe. Not
4176 * available on all platforms.
4178 * f = IO.popen("uname")
4179 * p f.readlines
4180 * puts "Parent is #{Process.pid}"
4181 * IO.popen("date") { |f| puts f.gets }
4182 * IO.popen("-") {|f| $stderr.puts "#{Process.pid} is here, f is #{f}"}
4183 * p $?
4184 * IO.popen(%w"sed -e s|^|<foo>| -e s&$&;zot;&", "r+") {|f|
4185 * f.puts "bar"; f.close_write; puts f.gets
4188 * <em>produces:</em>
4190 * ["Linux\n"]
4191 * Parent is 26166
4192 * Wed Apr 9 08:53:52 CDT 2003
4193 * 26169 is here, f is
4194 * 26166 is here, f is #<IO:0x401b3d44>
4195 * #<Process::Status: pid=26166,exited(0)>
4196 * <foo>bar;zot;
4199 static VALUE
4200 rb_io_s_popen(int argc, VALUE *argv, VALUE klass)
4202 const char *mode;
4203 VALUE pname, pmode, port, tmp;
4205 if (rb_scan_args(argc, argv, "11", &pname, &pmode) == 1) {
4206 mode = "r";
4208 else if (FIXNUM_P(pmode)) {
4209 mode = rb_io_modenum_mode(FIX2INT(pmode));
4211 else {
4212 mode = StringValueCStr(pmode);
4214 tmp = rb_check_array_type(pname);
4215 if (!NIL_P(tmp)) {
4216 tmp = rb_ary_dup(tmp);
4217 RBASIC(tmp)->klass = 0;
4218 port = pipe_open_v(RARRAY_LEN(tmp), RARRAY_PTR(tmp), mode);
4219 rb_ary_clear(tmp);
4221 else {
4222 SafeStringValue(pname);
4223 port = pipe_open_s(pname, mode);
4225 if (NIL_P(port)) {
4226 /* child */
4227 if (rb_block_given_p()) {
4228 rb_yield(Qnil);
4229 rb_io_flush(rb_stdout);
4230 rb_io_flush(rb_stderr);
4231 _exit(0);
4233 return Qnil;
4235 RBASIC(port)->klass = klass;
4236 if (rb_block_given_p()) {
4237 return rb_ensure(rb_yield, port, io_close, port);
4239 return port;
4242 static void
4243 io_set_encoding(VALUE io, VALUE opt)
4245 rb_io_t *fptr;
4246 VALUE encoding=Qnil, extenc=Qnil, intenc=Qnil;
4247 if (!NIL_P(opt)) {
4248 VALUE v;
4249 v = rb_hash_aref(opt, sym_encoding);
4250 if (!NIL_P(v)) encoding = v;
4251 v = rb_hash_aref(opt, sym_extenc);
4252 if (!NIL_P(v)) extenc = v;
4253 v = rb_hash_aref(opt, sym_intenc);
4254 if (!NIL_P(v)) intenc = v;
4256 if (!NIL_P(extenc)) {
4257 rb_encoding *extencoding = rb_to_encoding(extenc);
4258 GetOpenFile(io, fptr);
4259 fptr->enc = 0;
4260 fptr->enc2 = 0;
4261 if (!NIL_P(encoding)) {
4262 rb_warn("Ignoring encoding parameter '%s': external_encoding is used",
4263 RSTRING_PTR(encoding));
4265 if (!NIL_P(intenc)) {
4266 rb_encoding *intencoding = rb_to_encoding(intenc);
4267 if (extencoding == intencoding) {
4268 rb_warn("Ignoring internal encoding '%s': it is identical to external encoding '%s'",
4269 RSTRING_PTR(rb_inspect(intenc)),
4270 RSTRING_PTR(rb_inspect(extenc)));
4272 else {
4273 fptr->enc2 = intencoding;
4276 fptr->enc = extencoding;
4278 else {
4279 if (!NIL_P(intenc)) {
4280 rb_raise(rb_eArgError, "External encoding must be specified when internal encoding is given");
4282 if (!NIL_P(encoding)) {
4283 GetOpenFile(io, fptr);
4284 mode_enc(fptr, StringValueCStr(encoding));
4289 static VALUE
4290 rb_open_file(int argc, VALUE *argv, VALUE io)
4292 VALUE opt, fname, vmode, perm;
4293 const char *mode;
4294 int flags;
4295 unsigned int fmode;
4297 opt = rb_check_convert_type(argv[argc-1], T_HASH, "Hash", "to_hash");
4298 if (!NIL_P(opt)) {
4299 VALUE v;
4300 v = rb_hash_aref(opt, sym_mode);
4301 if (!NIL_P(v)) vmode = v;
4302 v = rb_hash_aref(opt, sym_perm);
4303 if (!NIL_P(v)) perm = v;
4304 argc -= 1;
4307 rb_scan_args(argc, argv, "12", &fname, &vmode, &perm);
4308 #if defined _WIN32 || defined __APPLE__
4310 static rb_encoding *fs_encoding;
4311 rb_encoding *fname_encoding = rb_enc_get(fname);
4312 if (!fs_encoding)
4313 fs_encoding = rb_filesystem_encoding();
4314 if (rb_usascii_encoding() != fname_encoding
4315 && rb_ascii8bit_encoding() != fname_encoding
4316 #if defined __APPLE__
4317 && rb_utf8_encoding() != fname_encoding
4318 #endif
4319 && fs_encoding != fname_encoding) {
4320 static VALUE fs_enc;
4321 if (!fs_enc)
4322 fs_enc = rb_enc_from_encoding(fs_encoding);
4323 fname = rb_str_transcode(fname, fs_enc);
4326 #endif
4327 FilePathValue(fname);
4329 if (FIXNUM_P(vmode) || !NIL_P(perm)) {
4330 if (FIXNUM_P(vmode)) {
4331 flags = FIX2INT(vmode);
4333 else {
4334 SafeStringValue(vmode);
4335 flags = rb_io_mode_modenum(StringValueCStr(vmode));
4337 fmode = NIL_P(perm) ? 0666 : NUM2UINT(perm);
4339 rb_file_sysopen_internal(io, RSTRING_PTR(fname), flags, fmode);
4341 else {
4342 mode = NIL_P(vmode) ? "r" : StringValueCStr(vmode);
4343 rb_file_open_internal(io, RSTRING_PTR(fname), mode);
4346 io_set_encoding(io, opt);
4347 return io;
4351 * call-seq:
4352 * IO.open(fd, mode_string="r" ) => io
4353 * IO.open(fd, mode_string="r" ) {|io| block } => obj
4355 * With no associated block, <code>open</code> is a synonym for
4356 * <code>IO::new</code>. If the optional code block is given, it will
4357 * be passed <i>io</i> as an argument, and the IO object will
4358 * automatically be closed when the block terminates. In this instance,
4359 * <code>IO::open</code> returns the value of the block.
4363 static VALUE
4364 rb_io_s_open(int argc, VALUE *argv, VALUE klass)
4366 VALUE io = rb_class_new_instance(argc, argv, klass);
4368 if (rb_block_given_p()) {
4369 return rb_ensure(rb_yield, io, io_close, io);
4372 return io;
4376 * call-seq:
4377 * IO.sysopen(path, [mode, [perm]]) => fixnum
4379 * Opens the given path, returning the underlying file descriptor as a
4380 * <code>Fixnum</code>.
4382 * IO.sysopen("testfile") #=> 3
4386 static VALUE
4387 rb_io_s_sysopen(int argc, VALUE *argv)
4389 VALUE fname, vmode, perm;
4390 int flags, fd;
4391 unsigned int fmode;
4392 char *path;
4394 rb_scan_args(argc, argv, "12", &fname, &vmode, &perm);
4395 FilePathValue(fname);
4397 if (NIL_P(vmode)) flags = O_RDONLY;
4398 else if (FIXNUM_P(vmode)) flags = FIX2INT(vmode);
4399 else {
4400 SafeStringValue(vmode);
4401 flags = rb_io_mode_modenum(StringValueCStr(vmode));
4403 if (NIL_P(perm)) fmode = 0666;
4404 else fmode = NUM2UINT(perm);
4406 RB_GC_GUARD(fname) = rb_str_new4(fname);
4407 path = RSTRING_PTR(fname);
4408 fd = rb_sysopen(path, flags, fmode);
4409 return INT2NUM(fd);
4413 * call-seq:
4414 * open(path [, mode_enc [, perm]] ) => io or nil
4415 * open(path [, mode_enc [, perm]] ) {|io| block } => obj
4417 * Creates an <code>IO</code> object connected to the given stream,
4418 * file, or subprocess.
4420 * If <i>path</i> does not start with a pipe character
4421 * (``<code>|</code>''), treat it as the name of a file to open using
4422 * the specified mode (defaulting to ``<code>r</code>'').
4424 * The mode_enc is
4425 * either a string or an integer. If it is an integer, it must be
4426 * bitwise-or of open(2) flags, such as File::RDWR or File::EXCL.
4427 * If it is a string, it is either "mode", "mode:ext_enc", or
4428 * "mode:ext_enc:int_enc".
4429 * The mode is one of the following:
4431 * r: read (default)
4432 * w: write
4433 * a: append
4435 * The mode can be followed by "b" (means binary-mode), or "+"
4436 * (means both reading and writing allowed) or both.
4437 * If ext_enc (external encoding) is specified,
4438 * read string will be tagged by the encoding in reading,
4439 * and output string will be converted
4440 * to the specified encoding in writing.
4441 * If two encoding names,
4442 * ext_enc and int_enc (external encoding and internal encoding),
4443 * are specified, the read string is converted from ext_enc
4444 * to int_enc then tagged with the int_enc in read mode,
4445 * and in write mode, the output string will be
4446 * converted from int_enc to ext_enc before writing.
4448 * If a file is being created, its initial permissions may be
4449 * set using the integer third parameter.
4451 * If a block is specified, it will be invoked with the
4452 * <code>File</code> object as a parameter, and the file will be
4453 * automatically closed when the block terminates. The call
4454 * returns the value of the block.
4456 * If <i>path</i> starts with a pipe character, a subprocess is
4457 * created, connected to the caller by a pair of pipes. The returned
4458 * <code>IO</code> object may be used to write to the standard input
4459 * and read from the standard output of this subprocess. If the command
4460 * following the ``<code>|</code>'' is a single minus sign, Ruby forks,
4461 * and this subprocess is connected to the parent. In the subprocess,
4462 * the <code>open</code> call returns <code>nil</code>. If the command
4463 * is not ``<code>-</code>'', the subprocess runs the command. If a
4464 * block is associated with an <code>open("|-")</code> call, that block
4465 * will be run twice---once in the parent and once in the child. The
4466 * block parameter will be an <code>IO</code> object in the parent and
4467 * <code>nil</code> in the child. The parent's <code>IO</code> object
4468 * will be connected to the child's <code>$stdin</code> and
4469 * <code>$stdout</code>. The subprocess will be terminated at the end
4470 * of the block.
4472 * open("testfile") do |f|
4473 * print f.gets
4474 * end
4476 * <em>produces:</em>
4478 * This is line one
4480 * Open a subprocess and read its output:
4482 * cmd = open("|date")
4483 * print cmd.gets
4484 * cmd.close
4486 * <em>produces:</em>
4488 * Wed Apr 9 08:56:31 CDT 2003
4490 * Open a subprocess running the same Ruby program:
4492 * f = open("|-", "w+")
4493 * if f == nil
4494 * puts "in Child"
4495 * exit
4496 * else
4497 * puts "Got: #{f.gets}"
4498 * end
4500 * <em>produces:</em>
4502 * Got: in Child
4504 * Open a subprocess using a block to receive the I/O object:
4506 * open("|-") do |f|
4507 * if f == nil
4508 * puts "in Child"
4509 * else
4510 * puts "Got: #{f.gets}"
4511 * end
4512 * end
4514 * <em>produces:</em>
4516 * Got: in Child
4519 static VALUE
4520 rb_f_open(int argc, VALUE *argv)
4522 ID to_open = 0;
4523 int redirect = Qfalse;
4525 if (argc >= 1) {
4526 CONST_ID(to_open, "to_open");
4527 if (rb_respond_to(argv[0], to_open)) {
4528 redirect = Qtrue;
4530 else {
4531 VALUE tmp = argv[0];
4532 FilePathValue(tmp);
4533 if (NIL_P(tmp)) {
4534 redirect = Qtrue;
4536 else {
4537 char *str = StringValuePtr(tmp);
4538 if (str && str[0] == '|') {
4539 argv[0] = rb_str_new(str+1, RSTRING_LEN(tmp)-1);
4540 OBJ_INFECT(argv[0], tmp);
4541 return rb_io_s_popen(argc, argv, rb_cIO);
4546 if (redirect) {
4547 VALUE io = rb_funcall2(argv[0], to_open, argc-1, argv+1);
4549 if (rb_block_given_p()) {
4550 return rb_ensure(rb_yield, io, io_close, io);
4552 return io;
4554 return rb_io_s_open(argc, argv, rb_cFile);
4557 static VALUE
4558 rb_io_open(const char *fname, const char *mode)
4560 if (fname[0] == '|') {
4561 VALUE cmd = rb_str_new2(fname+1);
4562 return pipe_open_s(cmd, mode);
4564 else {
4565 return rb_file_open(fname, mode);
4569 static VALUE
4570 rb_io_open_with_args(int argc, VALUE *argv)
4572 const char *mode;
4573 VALUE pname, pmode;
4575 if (rb_scan_args(argc, argv, "11", &pname, &pmode) == 1) {
4576 mode = "r";
4578 else if (FIXNUM_P(pmode)) {
4579 mode = rb_io_modenum_mode(FIX2INT(pmode));
4581 else {
4582 mode = StringValueCStr(pmode);
4584 return rb_io_open(StringValueCStr(pname), mode);
4587 static VALUE
4588 io_reopen(VALUE io, VALUE nfile)
4590 rb_io_t *fptr, *orig;
4591 int fd, fd2;
4592 off_t pos = 0;
4594 nfile = rb_io_get_io(nfile);
4595 if (rb_safe_level() >= 4 &&
4596 (!OBJ_UNTRUSTED(io) || !OBJ_UNTRUSTED(nfile))) {
4597 rb_raise(rb_eSecurityError, "Insecure: can't reopen");
4599 GetOpenFile(io, fptr);
4600 GetOpenFile(nfile, orig);
4602 if (fptr == orig) return io;
4603 if (IS_PREP_STDIO(fptr)) {
4604 if ((fptr->stdio_file == stdin && !(orig->mode & FMODE_READABLE)) ||
4605 (fptr->stdio_file == stdout && !(orig->mode & FMODE_WRITABLE)) ||
4606 (fptr->stdio_file == stderr && !(orig->mode & FMODE_WRITABLE))) {
4607 rb_raise(rb_eArgError,
4608 "%s can't change access mode from \"%s\" to \"%s\"",
4609 PREP_STDIO_NAME(fptr), rb_io_flags_mode(fptr->mode),
4610 rb_io_flags_mode(orig->mode));
4613 if (orig->mode & FMODE_READABLE) {
4614 pos = io_tell(orig);
4616 if (orig->mode & FMODE_WRITABLE) {
4617 io_fflush(orig);
4619 if (fptr->mode & FMODE_WRITABLE) {
4620 io_fflush(fptr);
4623 /* copy rb_io_t structure */
4624 fptr->mode = orig->mode | (fptr->mode & FMODE_PREP);
4625 fptr->pid = orig->pid;
4626 fptr->lineno = orig->lineno;
4627 if (fptr->path) free(fptr->path);
4628 if (orig->path) fptr->path = strdup(orig->path);
4629 else fptr->path = 0;
4630 fptr->finalize = orig->finalize;
4632 fd = fptr->fd;
4633 fd2 = orig->fd;
4634 if (fd != fd2) {
4635 if (IS_PREP_STDIO(fptr)) {
4636 /* need to keep stdio objects */
4637 if (dup2(fd2, fd) < 0)
4638 rb_sys_fail(orig->path);
4640 else {
4641 if (fptr->stdio_file)
4642 fclose(fptr->stdio_file);
4643 else
4644 close(fptr->fd);
4645 fptr->stdio_file = 0;
4646 fptr->fd = -1;
4647 if (dup2(fd2, fd) < 0)
4648 rb_sys_fail(orig->path);
4649 fptr->fd = fd;
4651 rb_thread_fd_close(fd);
4652 if ((orig->mode & FMODE_READABLE) && pos >= 0) {
4653 if (io_seek(fptr, pos, SEEK_SET) < 0) {
4654 rb_sys_fail(fptr->path);
4656 if (io_seek(orig, pos, SEEK_SET) < 0) {
4657 rb_sys_fail(orig->path);
4662 if (fptr->mode & FMODE_BINMODE) {
4663 rb_io_binmode(io);
4666 RBASIC(io)->klass = rb_obj_class(nfile);
4667 return io;
4671 * call-seq:
4672 * ios.reopen(other_IO) => ios
4673 * ios.reopen(path, mode_str) => ios
4675 * Reassociates <em>ios</em> with the I/O stream given in
4676 * <i>other_IO</i> or to a new stream opened on <i>path</i>. This may
4677 * dynamically change the actual class of this stream.
4679 * f1 = File.new("testfile")
4680 * f2 = File.new("testfile")
4681 * f2.readlines[0] #=> "This is line one\n"
4682 * f2.reopen(f1) #=> #<File:testfile>
4683 * f2.readlines[0] #=> "This is line one\n"
4686 static VALUE
4687 rb_io_reopen(int argc, VALUE *argv, VALUE file)
4689 VALUE fname, nmode;
4690 const char *mode;
4691 rb_io_t *fptr;
4693 rb_secure(4);
4694 if (rb_scan_args(argc, argv, "11", &fname, &nmode) == 1) {
4695 VALUE tmp = rb_io_check_io(fname);
4696 if (!NIL_P(tmp)) {
4697 return io_reopen(file, tmp);
4701 FilePathValue(fname);
4702 rb_io_taint_check(file);
4703 fptr = RFILE(file)->fptr;
4704 if (!fptr) {
4705 fptr = RFILE(file)->fptr = ALLOC(rb_io_t);
4706 MEMZERO(fptr, rb_io_t, 1);
4709 if (!NIL_P(nmode)) {
4710 int flags = rb_io_mode_flags(StringValueCStr(nmode));
4711 if (IS_PREP_STDIO(fptr) &&
4712 ((fptr->mode & FMODE_READWRITE) & (flags & FMODE_READWRITE)) !=
4713 (fptr->mode & FMODE_READWRITE)) {
4714 rb_raise(rb_eArgError,
4715 "%s can't change access mode from \"%s\" to \"%s\"",
4716 PREP_STDIO_NAME(fptr), rb_io_flags_mode(fptr->mode),
4717 rb_io_flags_mode(flags));
4719 fptr->mode = flags;
4720 rb_io_mode_enc(fptr, StringValueCStr(nmode));
4723 if (fptr->path) {
4724 free(fptr->path);
4725 fptr->path = 0;
4728 fptr->path = strdup(StringValueCStr(fname));
4729 mode = rb_io_flags_mode(fptr->mode);
4730 if (fptr->fd < 0) {
4731 fptr->fd = rb_sysopen(fptr->path, rb_io_mode_modenum(mode), 0666);
4732 fptr->stdio_file = 0;
4733 return file;
4736 if (fptr->mode & FMODE_WRITABLE) {
4737 io_fflush(fptr);
4739 fptr->rbuf_off = fptr->rbuf_len = 0;
4741 if (fptr->stdio_file) {
4742 if (freopen(fptr->path, mode, fptr->stdio_file) == 0) {
4743 rb_sys_fail(fptr->path);
4745 fptr->fd = fileno(fptr->stdio_file);
4746 #ifdef USE_SETVBUF
4747 if (setvbuf(fptr->stdio_file, NULL, _IOFBF, 0) != 0)
4748 rb_warn("setvbuf() can't be honoured for %s", fptr->path);
4749 #endif
4751 else {
4752 if (close(fptr->fd) < 0)
4753 rb_sys_fail(fptr->path);
4754 fptr->fd = -1;
4755 fptr->fd = rb_sysopen(fptr->path, rb_io_mode_modenum(mode), 0666);
4758 return file;
4761 /* :nodoc: */
4762 static VALUE
4763 rb_io_init_copy(VALUE dest, VALUE io)
4765 rb_io_t *fptr, *orig;
4766 int fd;
4767 VALUE write_io;
4769 io = rb_io_get_io(io);
4770 if (dest == io) return dest;
4771 GetOpenFile(io, orig);
4772 MakeOpenFile(dest, fptr);
4774 rb_io_flush(io);
4776 /* copy rb_io_t structure */
4777 fptr->mode = orig->mode & ~FMODE_PREP;
4778 fptr->pid = orig->pid;
4779 fptr->lineno = orig->lineno;
4780 if (orig->path) fptr->path = strdup(orig->path);
4781 fptr->finalize = orig->finalize;
4783 fd = ruby_dup(orig->fd);
4784 fptr->fd = fd;
4785 io_seek(fptr, io_tell(orig), SEEK_SET);
4786 if (fptr->mode & FMODE_BINMODE) {
4787 rb_io_binmode(dest);
4790 write_io = GetWriteIO(io);
4791 if (io != write_io) {
4792 write_io = rb_obj_dup(write_io);
4793 fptr->tied_io_for_writing = write_io;
4794 rb_ivar_set(dest, rb_intern("@tied_io_for_writing"), write_io);
4797 return dest;
4801 * call-seq:
4802 * ios.printf(format_string [, obj, ...] ) => nil
4804 * Formats and writes to <em>ios</em>, converting parameters under
4805 * control of the format string. See <code>Kernel#sprintf</code>
4806 * for details.
4809 VALUE
4810 rb_io_printf(int argc, VALUE *argv, VALUE out)
4812 rb_io_write(out, rb_f_sprintf(argc, argv));
4813 return Qnil;
4817 * call-seq:
4818 * printf(io, string [, obj ... ] ) => nil
4819 * printf(string [, obj ... ] ) => nil
4821 * Equivalent to:
4822 * io.write(sprintf(string, obj, ...)
4823 * or
4824 * $stdout.write(sprintf(string, obj, ...)
4827 static VALUE
4828 rb_f_printf(int argc, VALUE *argv)
4830 VALUE out;
4832 if (argc == 0) return Qnil;
4833 if (TYPE(argv[0]) == T_STRING) {
4834 out = rb_stdout;
4836 else {
4837 out = argv[0];
4838 argv++;
4839 argc--;
4841 rb_io_write(out, rb_f_sprintf(argc, argv));
4843 return Qnil;
4847 * call-seq:
4848 * ios.print() => nil
4849 * ios.print(obj, ...) => nil
4851 * Writes the given object(s) to <em>ios</em>. The stream must be
4852 * opened for writing. If the output record separator (<code>$\\</code>)
4853 * is not <code>nil</code>, it will be appended to the output. If no
4854 * arguments are given, prints <code>$_</code>. Objects that aren't
4855 * strings will be converted by calling their <code>to_s</code> method.
4856 * With no argument, prints the contents of the variable <code>$_</code>.
4857 * Returns <code>nil</code>.
4859 * $stdout.print("This is ", 100, " percent.\n")
4861 * <em>produces:</em>
4863 * This is 100 percent.
4866 VALUE
4867 rb_io_print(int argc, VALUE *argv, VALUE out)
4869 int i;
4870 VALUE line;
4872 /* if no argument given, print `$_' */
4873 if (argc == 0) {
4874 argc = 1;
4875 line = rb_lastline_get();
4876 argv = &line;
4878 for (i=0; i<argc; i++) {
4879 rb_io_write(out, argv[i]);
4880 if (!NIL_P(rb_output_fs)) {
4881 rb_io_write(out, rb_output_fs);
4884 if (argc > 0 && !NIL_P(rb_output_rs)) {
4885 rb_io_write(out, rb_output_rs);
4888 return Qnil;
4892 * call-seq:
4893 * print(obj, ...) => nil
4895 * Prints each object in turn to <code>$stdout</code>. If the output
4896 * field separator (<code>$,</code>) is not +nil+, its
4897 * contents will appear between each field. If the output record
4898 * separator (<code>$\\</code>) is not +nil+, it will be
4899 * appended to the output. If no arguments are given, prints
4900 * <code>$_</code>. Objects that aren't strings will be converted by
4901 * calling their <code>to_s</code> method.
4903 * print "cat", [1,2,3], 99, "\n"
4904 * $, = ", "
4905 * $\ = "\n"
4906 * print "cat", [1,2,3], 99
4908 * <em>produces:</em>
4910 * cat12399
4911 * cat, 1, 2, 3, 99
4914 static VALUE
4915 rb_f_print(int argc, VALUE *argv)
4917 rb_io_print(argc, argv, rb_stdout);
4918 return Qnil;
4922 * call-seq:
4923 * ios.putc(obj) => obj
4925 * If <i>obj</i> is <code>Numeric</code>, write the character whose
4926 * code is <i>obj</i>, otherwise write the first character of the
4927 * string representation of <i>obj</i> to <em>ios</em>.
4929 * $stdout.putc "A"
4930 * $stdout.putc 65
4932 * <em>produces:</em>
4934 * AA
4937 static VALUE
4938 rb_io_putc(VALUE io, VALUE ch)
4940 char c = NUM2CHR(ch);
4942 rb_io_write(io, rb_str_new(&c, 1));
4943 return ch;
4947 * call-seq:
4948 * putc(int) => int
4950 * Equivalent to:
4952 * $stdout.putc(int)
4955 static VALUE
4956 rb_f_putc(VALUE recv, VALUE ch)
4958 if (recv == rb_stdout) {
4959 return rb_io_putc(recv, ch);
4961 return rb_funcall2(rb_stdout, rb_intern("putc"), 1, &ch);
4964 static VALUE
4965 io_puts_ary(VALUE ary, VALUE out, int recur)
4967 VALUE tmp;
4968 long i;
4970 if (recur) {
4971 tmp = rb_str_new2("[...]");
4972 rb_io_puts(1, &tmp, out);
4973 return Qnil;
4975 for (i=0; i<RARRAY_LEN(ary); i++) {
4976 tmp = RARRAY_PTR(ary)[i];
4977 rb_io_puts(1, &tmp, out);
4979 return Qnil;
4983 * call-seq:
4984 * ios.puts(obj, ...) => nil
4986 * Writes the given objects to <em>ios</em> as with
4987 * <code>IO#print</code>. Writes a record separator (typically a
4988 * newline) after any that do not already end with a newline sequence.
4989 * If called with an array argument, writes each element on a new line.
4990 * If called without arguments, outputs a single record separator.
4992 * $stdout.puts("this", "is", "a", "test")
4994 * <em>produces:</em>
4996 * this
4997 * is
4999 * test
5002 VALUE
5003 rb_io_puts(int argc, VALUE *argv, VALUE out)
5005 int i;
5006 VALUE line;
5008 /* if no argument given, print newline. */
5009 if (argc == 0) {
5010 rb_io_write(out, rb_default_rs);
5011 return Qnil;
5013 for (i=0; i<argc; i++) {
5014 line = rb_check_array_type(argv[i]);
5015 if (!NIL_P(line)) {
5016 rb_exec_recursive(io_puts_ary, line, out);
5017 continue;
5019 line = rb_obj_as_string(argv[i]);
5020 rb_io_write(out, line);
5021 if (RSTRING_LEN(line) == 0 ||
5022 RSTRING_PTR(line)[RSTRING_LEN(line)-1] != '\n') {
5023 rb_io_write(out, rb_default_rs);
5027 return Qnil;
5031 * call-seq:
5032 * puts(obj, ...) => nil
5034 * Equivalent to
5036 * $stdout.puts(obj, ...)
5039 static VALUE
5040 rb_f_puts(int argc, VALUE *argv, VALUE recv)
5042 if (recv == rb_stdout) {
5043 return rb_io_puts(argc, argv, recv);
5045 return rb_funcall2(rb_stdout, rb_intern("puts"), argc, argv);
5048 void
5049 rb_p(VALUE obj) /* for debug print within C code */
5051 VALUE str = rb_obj_as_string(rb_inspect(obj));
5052 rb_str_buf_append(str, rb_default_rs);
5053 rb_io_write(rb_stdout, str);
5057 * call-seq:
5058 * p(obj) => obj
5059 * p(obj1, obj2, ...) => [obj, ...]
5060 * p() => nil
5062 * For each object, directly writes
5063 * _obj_.+inspect+ followed by the current output
5064 * record separator to the program's standard output.
5066 * S = Struct.new(:name, :state)
5067 * s = S['dave', 'TX']
5068 * p s
5070 * <em>produces:</em>
5072 * #<S name="dave", state="TX">
5075 static VALUE
5076 rb_f_p(int argc, VALUE *argv, VALUE self)
5078 int i;
5079 VALUE ret = Qnil;
5081 for (i=0; i<argc; i++) {
5082 rb_p(argv[i]);
5084 if (argc == 1) {
5085 ret = argv[0];
5087 else if (argc > 1) {
5088 ret = rb_ary_new4(argc, argv);
5090 if (TYPE(rb_stdout) == T_FILE) {
5091 rb_io_flush(rb_stdout);
5093 return ret;
5097 * call-seq:
5098 * obj.display(port=$>) => nil
5100 * Prints <i>obj</i> on the given port (default <code>$></code>).
5101 * Equivalent to:
5103 * def display(port=$>)
5104 * port.write self
5105 * end
5107 * For example:
5109 * 1.display
5110 * "cat".display
5111 * [ 4, 5, 6 ].display
5112 * puts
5114 * <em>produces:</em>
5116 * 1cat456
5119 static VALUE
5120 rb_obj_display(int argc, VALUE *argv, VALUE self)
5122 VALUE out;
5124 if (argc == 0) {
5125 out = rb_stdout;
5127 else {
5128 rb_scan_args(argc, argv, "01", &out);
5130 rb_io_write(out, self);
5132 return Qnil;
5135 void
5136 rb_write_error2(const char *mesg, long len)
5138 if (rb_stderr == orig_stderr || RFILE(orig_stderr)->fptr->fd < 0) {
5139 fwrite(mesg, sizeof(char), len, stderr);
5141 else {
5142 rb_io_write(rb_stderr, rb_str_new(mesg, len));
5146 void
5147 rb_write_error(const char *mesg)
5149 rb_write_error2(mesg, strlen(mesg));
5152 static void
5153 must_respond_to(ID mid, VALUE val, ID id)
5155 if (!rb_respond_to(val, mid)) {
5156 rb_raise(rb_eTypeError, "%s must have %s method, %s given",
5157 rb_id2name(id), rb_id2name(mid),
5158 rb_obj_classname(val));
5162 static void
5163 stdout_setter(VALUE val, ID id, VALUE *variable)
5165 must_respond_to(id_write, val, id);
5166 *variable = val;
5169 static VALUE
5170 prep_io(int fd, int mode, VALUE klass, const char *path)
5172 rb_io_t *fp;
5173 VALUE io = io_alloc(klass);
5175 MakeOpenFile(io, fp);
5176 fp->fd = fd;
5177 #ifdef __CYGWIN__
5178 if (!isatty(fd)) {
5179 mode |= O_BINARY;
5180 setmode(fd, O_BINARY);
5182 #endif
5183 fp->mode = mode;
5184 io_check_tty(fp);
5185 if (path) fp->path = strdup(path);
5187 return io;
5190 VALUE
5191 rb_io_fdopen(int fd, int mode, const char *path)
5193 VALUE klass = rb_cIO;
5195 if (path && strcmp(path, "-")) klass = rb_cFile;
5196 return prep_io(fd, rb_io_modenum_flags(mode), klass, path);
5199 static VALUE
5200 prep_stdio(FILE *f, int mode, VALUE klass, const char *path)
5202 rb_io_t *fptr;
5203 VALUE io = prep_io(fileno(f), mode|FMODE_PREP, klass, path);
5205 GetOpenFile(io, fptr);
5206 fptr->stdio_file = f;
5208 return io;
5211 FILE *
5212 rb_io_stdio_file(rb_io_t *fptr)
5214 if (!fptr->stdio_file) {
5215 fptr->stdio_file = rb_fdopen(fptr->fd, rb_io_flags_mode(fptr->mode));
5217 return fptr->stdio_file;
5221 * call-seq:
5222 * IO.new(fd, mode) => io
5224 * Returns a new <code>IO</code> object (a stream) for the given
5225 * <code>IO</code> object or integer file descriptor and mode
5226 * string. See also <code>IO#fileno</code> and
5227 * <code>IO::for_fd</code>.
5229 * puts IO.new($stdout).fileno # => 1
5231 * a = IO.new(2,"w") # '2' is standard error
5232 * $stderr.puts "Hello"
5233 * a.puts "World"
5235 * <em>produces:</em>
5237 * Hello
5238 * World
5241 static VALUE
5242 rb_io_initialize(int argc, VALUE *argv, VALUE io)
5244 VALUE fnum, mode, orig;
5245 rb_io_t *fp, *ofp = NULL;
5246 int fd, fmode, flags = O_RDONLY;
5248 rb_secure(4);
5249 rb_scan_args(argc, argv, "11", &fnum, &mode);
5250 if (argc == 2) {
5251 if (FIXNUM_P(mode)) {
5252 flags = FIX2LONG(mode);
5254 else {
5255 SafeStringValue(mode);
5256 flags = rb_io_mode_modenum(StringValueCStr(mode));
5259 orig = rb_io_check_io(fnum);
5260 if (NIL_P(orig)) {
5261 fd = NUM2INT(fnum);
5262 UPDATE_MAXFD(fd);
5263 if (argc != 2) {
5264 #if defined(HAVE_FCNTL) && defined(F_GETFL)
5265 flags = fcntl(fd, F_GETFL);
5266 if (flags == -1) rb_sys_fail(0);
5267 #endif
5269 MakeOpenFile(io, fp);
5270 fp->fd = fd;
5271 fp->mode = rb_io_modenum_flags(flags);
5272 io_check_tty(fp);
5274 else if (RFILE(io)->fptr) {
5275 rb_raise(rb_eRuntimeError, "reinitializing IO");
5277 else {
5278 GetOpenFile(orig, ofp);
5279 if (ofp->refcnt == LONG_MAX) {
5280 VALUE s = rb_inspect(orig);
5281 rb_raise(rb_eIOError, "too many shared IO for %s", StringValueCStr(s));
5283 if (argc == 2) {
5284 fmode = rb_io_modenum_flags(flags);
5285 if ((ofp->mode ^ fmode) & (FMODE_READWRITE|FMODE_BINMODE)) {
5286 if (FIXNUM_P(mode)) {
5287 rb_raise(rb_eArgError, "incompatible mode 0%o", flags);
5289 else {
5290 rb_raise(rb_eArgError, "incompatible mode \"%s\"", RSTRING_PTR(mode));
5294 ofp->refcnt++;
5295 RFILE(io)->fptr = ofp;
5298 return io;
5303 * call-seq:
5304 * File.new(filename, mode="r") => file
5305 * File.new(filename [, mode [, perm]]) => file
5308 * Opens the file named by _filename_ according to
5309 * _mode_ (default is ``r'') and returns a new
5310 * <code>File</code> object. See the description of class +IO+ for
5311 * a description of _mode_. The file mode may optionally be
5312 * specified as a +Fixnum+ by _or_-ing together the
5313 * flags (O_RDONLY etc, again described under +IO+). Optional
5314 * permission bits may be given in _perm_. These mode and permission
5315 * bits are platform dependent; on Unix systems, see
5316 * <code>open(2)</code> for details.
5318 * f = File.new("testfile", "r")
5319 * f = File.new("newfile", "w+")
5320 * f = File.new("newfile", File::CREAT|File::TRUNC|File::RDWR, 0644)
5323 static VALUE
5324 rb_file_initialize(int argc, VALUE *argv, VALUE io)
5326 if (RFILE(io)->fptr) {
5327 rb_raise(rb_eRuntimeError, "reinitializing File");
5329 if (0 < argc && argc < 3) {
5330 VALUE fd = rb_check_convert_type(argv[0], T_FIXNUM, "Fixnum", "to_int");
5332 if (!NIL_P(fd)) {
5333 argv[0] = fd;
5334 return rb_io_initialize(argc, argv, io);
5337 rb_open_file(argc, argv, io);
5339 return io;
5343 * call-seq:
5344 * IO.new(fd, mode_string) => io
5346 * Returns a new <code>IO</code> object (a stream) for the given
5347 * integer file descriptor and mode string. See also
5348 * <code>IO#fileno</code> and <code>IO::for_fd</code>.
5350 * a = IO.new(2,"w") # '2' is standard error
5351 * $stderr.puts "Hello"
5352 * a.puts "World"
5354 * <em>produces:</em>
5356 * Hello
5357 * World
5360 static VALUE
5361 rb_io_s_new(int argc, VALUE *argv, VALUE klass)
5363 if (rb_block_given_p()) {
5364 const char *cname = rb_class2name(klass);
5366 rb_warn("%s::new() does not take block; use %s::open() instead",
5367 cname, cname);
5369 return rb_class_new_instance(argc, argv, klass);
5374 * call-seq:
5375 * IO.for_fd(fd, mode) => io
5377 * Synonym for <code>IO::new</code>.
5381 static VALUE
5382 rb_io_s_for_fd(int argc, VALUE *argv, VALUE klass)
5384 VALUE io = rb_obj_alloc(klass);
5385 rb_io_initialize(argc, argv, io);
5386 return io;
5389 static void
5390 argf_mark(void *ptr)
5392 struct argf *p = ptr;
5393 rb_gc_mark(p->filename);
5394 rb_gc_mark(p->current_file);
5395 rb_gc_mark(p->lineno);
5396 rb_gc_mark(p->argv);
5399 static void
5400 argf_free(void *ptr)
5402 struct argf *p = ptr;
5403 free(p->inplace);
5406 static inline void
5407 argf_init(struct argf *p, VALUE v)
5409 p->filename = Qnil;
5410 p->current_file = Qnil;
5411 p->lineno = Qnil;
5412 p->argv = v;
5415 static VALUE
5416 argf_alloc(VALUE klass)
5418 struct argf *p;
5419 VALUE argf = Data_Make_Struct(klass, struct argf, argf_mark, argf_free, p);
5421 argf_init(p, Qnil);
5422 return argf;
5425 #undef rb_argv
5426 #define filename ARGF.filename
5427 #define current_file ARGF.current_file
5428 #define gets_lineno ARGF.gets_lineno
5429 #define init_p ARGF.init_p
5430 #define next_p ARGF.next_p
5431 #define lineno ARGF.lineno
5432 #define ruby_inplace_mode ARGF.inplace
5433 #define argf_binmode ARGF.binmode
5434 #define argf_enc ARGF.enc
5435 #define argf_enc2 ARGF.enc2
5436 #define rb_argv ARGF.argv
5438 static VALUE
5439 argf_initialize(VALUE argf, VALUE argv)
5441 memset(&ARGF, 0, sizeof(ARGF));
5442 argf_init(&ARGF, argv);
5444 return argf;
5447 static VALUE
5448 argf_initialize_copy(VALUE argf, VALUE orig)
5450 ARGF = argf_of(orig);
5451 rb_argv = rb_obj_dup(rb_argv);
5452 if (ARGF.inplace) {
5453 const char *inplace = ARGF.inplace;
5454 ARGF.inplace = 0;
5455 ARGF.inplace = ruby_strdup(inplace);
5457 return argf;
5460 static VALUE
5461 argf_set_lineno(VALUE argf, VALUE val)
5463 gets_lineno = NUM2INT(val);
5464 lineno = INT2FIX(gets_lineno);
5465 return Qnil;
5468 static VALUE
5469 argf_lineno(VALUE argf)
5471 return lineno;
5474 static VALUE
5475 argf_forward(int argc, VALUE *argv, VALUE argf)
5477 return rb_funcall3(current_file, rb_frame_this_func(), argc, argv);
5480 #define next_argv() argf_next_argv(argf)
5481 #define ARGF_GENERIC_INPUT_P() \
5482 (current_file == rb_stdin && TYPE(current_file) != T_FILE)
5483 #define ARGF_FORWARD(argc, argv) do {\
5484 if (ARGF_GENERIC_INPUT_P())\
5485 return argf_forward(argc, argv, argf);\
5486 } while (0)
5487 #define NEXT_ARGF_FORWARD(argc, argv) do {\
5488 if (!next_argv()) return Qnil;\
5489 ARGF_FORWARD(argc, argv);\
5490 } while (0)
5492 static void
5493 argf_close(VALUE file)
5495 rb_funcall3(file, rb_intern("close"), 0, 0);
5498 static int
5499 argf_next_argv(VALUE argf)
5501 char *fn;
5502 rb_io_t *fptr;
5503 int stdout_binmode = 0;
5505 if (TYPE(rb_stdout) == T_FILE) {
5506 GetOpenFile(rb_stdout, fptr);
5507 if (fptr->mode & FMODE_BINMODE)
5508 stdout_binmode = 1;
5511 if (init_p == 0) {
5512 if (!NIL_P(rb_argv) && RARRAY_LEN(rb_argv) > 0) {
5513 next_p = 1;
5515 else {
5516 next_p = -1;
5518 init_p = 1;
5519 gets_lineno = 0;
5522 if (next_p == 1) {
5523 next_p = 0;
5524 retry:
5525 if (RARRAY_LEN(rb_argv) > 0) {
5526 filename = rb_ary_shift(rb_argv);
5527 fn = StringValueCStr(filename);
5528 if (strlen(fn) == 1 && fn[0] == '-') {
5529 current_file = rb_stdin;
5530 if (ruby_inplace_mode) {
5531 rb_warn("Can't do inplace edit for stdio; skipping");
5532 goto retry;
5535 else {
5536 int fr = rb_sysopen(fn, O_RDONLY, 0);
5538 if (ruby_inplace_mode) {
5539 struct stat st;
5540 #ifndef NO_SAFE_RENAME
5541 struct stat st2;
5542 #endif
5543 VALUE str;
5544 int fw;
5546 if (TYPE(rb_stdout) == T_FILE && rb_stdout != orig_stdout) {
5547 rb_io_close(rb_stdout);
5549 fstat(fr, &st);
5550 if (*ruby_inplace_mode) {
5551 str = rb_str_new2(fn);
5552 #ifdef NO_LONG_FNAME
5553 ruby_add_suffix(str, ruby_inplace_mode);
5554 #else
5555 rb_str_cat2(str, ruby_inplace_mode);
5556 #endif
5557 #ifdef NO_SAFE_RENAME
5558 (void)close(fr);
5559 (void)unlink(RSTRING_PTR(str));
5560 (void)rename(fn, RSTRING_PTR(str));
5561 fr = rb_sysopen(RSTRING_PTR(str), O_RDONLY, 0);
5562 #else
5563 if (rename(fn, RSTRING_PTR(str)) < 0) {
5564 rb_warn("Can't rename %s to %s: %s, skipping file",
5565 fn, RSTRING_PTR(str), strerror(errno));
5566 close(fr);
5567 goto retry;
5569 #endif
5571 else {
5572 #ifdef NO_SAFE_RENAME
5573 rb_fatal("Can't do inplace edit without backup");
5574 #else
5575 if (unlink(fn) < 0) {
5576 rb_warn("Can't remove %s: %s, skipping file",
5577 fn, strerror(errno));
5578 close(fr);
5579 goto retry;
5581 #endif
5583 fw = rb_sysopen(fn, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5584 #ifndef NO_SAFE_RENAME
5585 fstat(fw, &st2);
5586 #ifdef HAVE_FCHMOD
5587 fchmod(fw, st.st_mode);
5588 #else
5589 chmod(fn, st.st_mode);
5590 #endif
5591 if (st.st_uid!=st2.st_uid || st.st_gid!=st2.st_gid) {
5592 fchown(fw, st.st_uid, st.st_gid);
5594 #endif
5595 rb_stdout = prep_io(fw, FMODE_WRITABLE, rb_cFile, fn);
5596 if (stdout_binmode) rb_io_binmode(rb_stdout);
5598 current_file = prep_io(fr, FMODE_READABLE, rb_cFile, fn);
5600 if (argf_binmode) rb_io_binmode(current_file);
5601 if (argf_enc) {
5602 rb_io_t *fptr;
5604 GetOpenFile(current_file, fptr);
5605 fptr->enc = argf_enc;
5606 fptr->enc2 = argf_enc2;
5609 else {
5610 next_p = 1;
5611 return Qfalse;
5614 else if (next_p == -1) {
5615 current_file = rb_stdin;
5616 filename = rb_str_new2("-");
5617 if (ruby_inplace_mode) {
5618 rb_warn("Can't do inplace edit for stdio");
5619 rb_stdout = orig_stdout;
5622 return Qtrue;
5625 static VALUE
5626 argf_getline(int argc, VALUE *argv, VALUE argf)
5628 VALUE line;
5630 retry:
5631 if (!next_argv()) return Qnil;
5632 if (ARGF_GENERIC_INPUT_P()) {
5633 line = rb_funcall3(current_file, rb_intern("gets"), argc, argv);
5635 else {
5636 if (argc == 0 && rb_rs == rb_default_rs) {
5637 line = rb_io_gets(current_file);
5639 else {
5640 line = rb_io_getline(argc, argv, current_file);
5642 if (NIL_P(line) && next_p != -1) {
5643 argf_close(current_file);
5644 next_p = 1;
5645 goto retry;
5648 if (!NIL_P(line)) {
5649 gets_lineno++;
5650 lineno = INT2FIX(gets_lineno);
5652 return line;
5655 static VALUE
5656 argf_lineno_getter(ID id, VALUE *var)
5658 VALUE argf = *var;
5659 return lineno;
5662 static void
5663 argf_lineno_setter(VALUE val, ID id, VALUE *var)
5665 VALUE argf = *var;
5666 int n = NUM2INT(val);
5667 gets_lineno = n;
5668 lineno = INT2FIX(n);
5671 static VALUE argf_gets(int, VALUE *, VALUE);
5674 * call-seq:
5675 * gets(sep=$/) => string or nil
5676 * gets(limit) => string or nil
5677 * gets(sep,limit) => string or nil
5679 * Returns (and assigns to <code>$_</code>) the next line from the list
5680 * of files in +ARGV+ (or <code>$*</code>), or from standard input if
5681 * no files are present on the command line. Returns +nil+ at end of
5682 * file. The optional argument specifies the record separator. The
5683 * separator is included with the contents of each record. A separator
5684 * of +nil+ reads the entire contents, and a zero-length separator
5685 * reads the input one paragraph at a time, where paragraphs are
5686 * divided by two consecutive newlines. If the first argument is an
5687 * integer, or optional second argument is given, the returning string
5688 * would not be longer than the given value. If multiple filenames are
5689 * present in +ARGV+, +gets(nil)+ will read the contents one file at a
5690 * time.
5692 * ARGV << "testfile"
5693 * print while gets
5695 * <em>produces:</em>
5697 * This is line one
5698 * This is line two
5699 * This is line three
5700 * And so on...
5702 * The style of programming using <code>$_</code> as an implicit
5703 * parameter is gradually losing favor in the Ruby community.
5706 static VALUE
5707 rb_f_gets(int argc, VALUE *argv, VALUE recv)
5709 if (recv == argf) {
5710 return argf_gets(argc, argv, argf);
5712 return rb_funcall2(argf, rb_intern("gets"), argc, argv);
5715 static VALUE
5716 argf_gets(int argc, VALUE *argv, VALUE argf)
5718 VALUE line;
5720 line = argf_getline(argc, argv, argf);
5721 rb_lastline_set(line);
5722 return line;
5725 VALUE
5726 rb_gets(void)
5728 VALUE line;
5730 if (rb_rs != rb_default_rs) {
5731 return rb_f_gets(0, 0, argf);
5734 retry:
5735 if (!next_argv()) return Qnil;
5736 line = rb_io_gets(current_file);
5737 if (NIL_P(line) && next_p != -1) {
5738 rb_io_close(current_file);
5739 next_p = 1;
5740 goto retry;
5742 rb_lastline_set(line);
5743 if (!NIL_P(line)) {
5744 gets_lineno++;
5745 lineno = INT2FIX(gets_lineno);
5748 return line;
5751 static VALUE argf_readline(int, VALUE *, VALUE);
5754 * call-seq:
5755 * readline(sep=$/) => string
5756 * readline(limit) => string
5757 * readline(sep, limit) => string
5759 * Equivalent to <code>Kernel::gets</code>, except
5760 * +readline+ raises +EOFError+ at end of file.
5763 static VALUE
5764 rb_f_readline(int argc, VALUE *argv, VALUE recv)
5766 if (recv == argf) {
5767 return argf_readline(argc, argv, argf);
5769 return rb_funcall2(argf, rb_intern("readline"), argc, argv);
5772 static VALUE
5773 argf_readline(int argc, VALUE *argv, VALUE argf)
5775 VALUE line;
5777 if (!next_argv()) rb_eof_error();
5778 ARGF_FORWARD(argc, argv);
5779 line = argf_gets(argc, argv, argf);
5780 if (NIL_P(line)) {
5781 rb_eof_error();
5784 return line;
5787 static VALUE argf_readlines(int, VALUE *, VALUE);
5790 * call-seq:
5791 * readlines(sep=$/) => array
5792 * readlines(limit) => array
5793 * readlines(sep,limit) => array
5795 * Returns an array containing the lines returned by calling
5796 * <code>Kernel.gets(<i>sep</i>)</code> until the end of file.
5799 static VALUE
5800 rb_f_readlines(int argc, VALUE *argv, VALUE recv)
5802 if (recv == argf) {
5803 return argf_readlines(argc, argv, argf);
5805 return rb_funcall2(argf, rb_intern("readlines"), argc, argv);
5808 static VALUE
5809 argf_readlines(int argc, VALUE *argv, VALUE argf)
5811 VALUE line, ary;
5813 ary = rb_ary_new();
5814 while (!NIL_P(line = argf_getline(argc, argv, argf))) {
5815 rb_ary_push(ary, line);
5818 return ary;
5822 * call-seq:
5823 * `cmd` => string
5825 * Returns the standard output of running _cmd_ in a subshell.
5826 * The built-in syntax <code>%x{...}</code> uses
5827 * this method. Sets <code>$?</code> to the process status.
5829 * `date` #=> "Wed Apr 9 08:56:30 CDT 2003\n"
5830 * `ls testdir`.split[1] #=> "main.rb"
5831 * `echo oops && exit 99` #=> "oops\n"
5832 * $?.exitstatus #=> 99
5835 static VALUE
5836 rb_f_backquote(VALUE obj, VALUE str)
5838 volatile VALUE port;
5839 VALUE result;
5840 rb_io_t *fptr;
5842 SafeStringValue(str);
5843 port = pipe_open_s(str, "r");
5844 if (NIL_P(port)) return rb_str_new(0,0);
5846 GetOpenFile(port, fptr);
5847 result = read_all(fptr, remain_size(fptr), Qnil);
5848 rb_io_close(port);
5850 return result;
5853 #ifdef HAVE_SYS_SELECT_H
5854 #include <sys/select.h>
5855 #endif
5857 static VALUE
5858 select_internal(VALUE read, VALUE write, VALUE except, struct timeval *tp, rb_fdset_t *fds)
5860 VALUE res, list;
5861 fd_set *rp, *wp, *ep;
5862 rb_io_t *fptr;
5863 long i;
5864 int max = 0, n;
5865 int interrupt_flag = 0;
5866 int pending = 0;
5867 struct timeval timerec;
5869 if (!NIL_P(read)) {
5870 Check_Type(read, T_ARRAY);
5871 for (i=0; i<RARRAY_LEN(read); i++) {
5872 GetOpenFile(rb_io_get_io(RARRAY_PTR(read)[i]), fptr);
5873 rb_fd_set(fptr->fd, &fds[0]);
5874 if (READ_DATA_PENDING(fptr)) { /* check for buffered data */
5875 pending++;
5876 rb_fd_set(fptr->fd, &fds[3]);
5878 if (max < fptr->fd) max = fptr->fd;
5880 if (pending) { /* no blocking if there's buffered data */
5881 timerec.tv_sec = timerec.tv_usec = 0;
5882 tp = &timerec;
5884 rp = rb_fd_ptr(&fds[0]);
5886 else
5887 rp = 0;
5889 if (!NIL_P(write)) {
5890 Check_Type(write, T_ARRAY);
5891 for (i=0; i<RARRAY_LEN(write); i++) {
5892 VALUE write_io = GetWriteIO(rb_io_get_io(RARRAY_PTR(write)[i]));
5893 GetOpenFile(write_io, fptr);
5894 rb_fd_set(fptr->fd, &fds[1]);
5895 if (max < fptr->fd) max = fptr->fd;
5897 wp = rb_fd_ptr(&fds[1]);
5899 else
5900 wp = 0;
5902 if (!NIL_P(except)) {
5903 Check_Type(except, T_ARRAY);
5904 for (i=0; i<RARRAY_LEN(except); i++) {
5905 VALUE io = rb_io_get_io(RARRAY_PTR(except)[i]);
5906 VALUE write_io = GetWriteIO(io);
5907 GetOpenFile(io, fptr);
5908 rb_fd_set(fptr->fd, &fds[2]);
5909 if (max < fptr->fd) max = fptr->fd;
5910 if (io != write_io) {
5911 GetOpenFile(write_io, fptr);
5912 rb_fd_set(fptr->fd, &fds[2]);
5913 if (max < fptr->fd) max = fptr->fd;
5916 ep = rb_fd_ptr(&fds[2]);
5918 else {
5919 ep = 0;
5922 max++;
5924 n = rb_thread_select(max, rp, wp, ep, tp);
5925 if (n < 0) {
5926 rb_sys_fail(0);
5928 if (!pending && n == 0) return Qnil; /* returns nil on timeout */
5930 res = rb_ary_new2(3);
5931 rb_ary_push(res, rp?rb_ary_new():rb_ary_new2(0));
5932 rb_ary_push(res, wp?rb_ary_new():rb_ary_new2(0));
5933 rb_ary_push(res, ep?rb_ary_new():rb_ary_new2(0));
5935 if (interrupt_flag == 0) {
5936 if (rp) {
5937 list = RARRAY_PTR(res)[0];
5938 for (i=0; i< RARRAY_LEN(read); i++) {
5939 VALUE obj = rb_ary_entry(read, i);
5940 VALUE io = rb_io_get_io(obj);
5941 GetOpenFile(io, fptr);
5942 if (rb_fd_isset(fptr->fd, &fds[0]) ||
5943 rb_fd_isset(fptr->fd, &fds[3])) {
5944 rb_ary_push(list, obj);
5949 if (wp) {
5950 list = RARRAY_PTR(res)[1];
5951 for (i=0; i< RARRAY_LEN(write); i++) {
5952 VALUE obj = rb_ary_entry(write, i);
5953 VALUE io = rb_io_get_io(obj);
5954 VALUE write_io = GetWriteIO(io);
5955 GetOpenFile(write_io, fptr);
5956 if (rb_fd_isset(fptr->fd, &fds[1])) {
5957 rb_ary_push(list, obj);
5962 if (ep) {
5963 list = RARRAY_PTR(res)[2];
5964 for (i=0; i< RARRAY_LEN(except); i++) {
5965 VALUE obj = rb_ary_entry(except, i);
5966 VALUE io = rb_io_get_io(obj);
5967 VALUE write_io = GetWriteIO(io);
5968 GetOpenFile(io, fptr);
5969 if (rb_fd_isset(fptr->fd, &fds[2])) {
5970 rb_ary_push(list, obj);
5972 else if (io != write_io) {
5973 GetOpenFile(write_io, fptr);
5974 if (rb_fd_isset(fptr->fd, &fds[2])) {
5975 rb_ary_push(list, obj);
5982 return res; /* returns an empty array on interrupt */
5985 struct select_args {
5986 VALUE read, write, except;
5987 struct timeval *timeout;
5988 rb_fdset_t fdsets[4];
5991 #ifdef HAVE_RB_FD_INIT
5992 static VALUE
5993 select_call(VALUE arg)
5995 struct select_args *p = (struct select_args *)arg;
5997 return select_internal(p->read, p->write, p->except, p->timeout, p->fdsets);
6000 static VALUE
6001 select_end(VALUE arg)
6003 struct select_args *p = (struct select_args *)arg;
6004 int i;
6006 for (i = 0; i < sizeof(p->fdsets) / sizeof(p->fdsets[0]); ++i)
6007 rb_fd_term(&p->fdsets[i]);
6008 return Qnil;
6010 #endif
6013 * call-seq:
6014 * IO.select(read_array
6015 * [, write_array
6016 * [, error_array
6017 * [, timeout]]] ) => array or nil
6019 * See <code>Kernel#select</code>.
6022 static VALUE
6023 rb_f_select(int argc, VALUE *argv, VALUE obj)
6025 VALUE timeout;
6026 struct select_args args;
6027 struct timeval timerec;
6028 int i;
6030 rb_scan_args(argc, argv, "13", &args.read, &args.write, &args.except, &timeout);
6031 if (NIL_P(timeout)) {
6032 args.timeout = 0;
6034 else {
6035 timerec = rb_time_interval(timeout);
6036 args.timeout = &timerec;
6039 for (i = 0; i < sizeof(args.fdsets) / sizeof(args.fdsets[0]); ++i)
6040 rb_fd_init(&args.fdsets[i]);
6042 #ifdef HAVE_RB_FD_INIT
6043 return rb_ensure(select_call, (VALUE)&args, select_end, (VALUE)&args);
6044 #else
6045 return select_internal(args.read, args.write, args.except,
6046 args.timeout, args.fdsets);
6047 #endif
6051 #if !defined(MSDOS) && !defined(__human68k__)
6052 static int
6053 io_cntl(int fd, int cmd, long narg, int io_p)
6055 int retval;
6057 #ifdef HAVE_FCNTL
6058 TRAP_BEG;
6059 # if defined(__CYGWIN__)
6060 retval = io_p?ioctl(fd, cmd, (void*)narg):fcntl(fd, cmd, narg);
6061 # else
6062 retval = io_p?ioctl(fd, cmd, narg):fcntl(fd, cmd, narg);
6063 # endif
6064 TRAP_END;
6065 #else
6066 if (!io_p) {
6067 rb_notimplement();
6069 TRAP_BEG;
6070 retval = ioctl(fd, cmd, narg);
6071 TRAP_END;
6072 #endif
6073 return retval;
6075 #endif
6077 static VALUE
6078 rb_io_ctl(VALUE io, VALUE req, VALUE arg, int io_p)
6080 #if !defined(MSDOS) && !defined(__human68k__)
6081 int cmd = NUM2ULONG(req);
6082 rb_io_t *fptr;
6083 long len = 0;
6084 long narg = 0;
6085 int retval;
6087 rb_secure(2);
6089 if (NIL_P(arg) || arg == Qfalse) {
6090 narg = 0;
6092 else if (FIXNUM_P(arg)) {
6093 narg = FIX2LONG(arg);
6095 else if (arg == Qtrue) {
6096 narg = 1;
6098 else {
6099 VALUE tmp = rb_check_string_type(arg);
6101 if (NIL_P(tmp)) {
6102 narg = NUM2LONG(arg);
6104 else {
6105 arg = tmp;
6106 #ifdef IOCPARM_MASK
6107 #ifndef IOCPARM_LEN
6108 #define IOCPARM_LEN(x) (((x) >> 16) & IOCPARM_MASK)
6109 #endif
6110 #endif
6111 #ifdef IOCPARM_LEN
6112 len = IOCPARM_LEN(cmd); /* on BSDish systems we're safe */
6113 #else
6114 len = 256; /* otherwise guess at what's safe */
6115 #endif
6116 rb_str_modify(arg);
6118 if (len <= RSTRING_LEN(arg)) {
6119 len = RSTRING_LEN(arg);
6121 if (RSTRING_LEN(arg) < len) {
6122 rb_str_resize(arg, len+1);
6124 RSTRING_PTR(arg)[len] = 17; /* a little sanity check here */
6125 narg = (long)RSTRING_PTR(arg);
6128 GetOpenFile(io, fptr);
6129 retval = io_cntl(fptr->fd, cmd, narg, io_p);
6130 if (retval < 0) rb_sys_fail(fptr->path);
6131 if (TYPE(arg) == T_STRING && RSTRING_PTR(arg)[len] != 17) {
6132 rb_raise(rb_eArgError, "return value overflowed string");
6135 if (!io_p && cmd == F_SETFL) {
6136 if (narg & O_NONBLOCK) {
6137 fptr->mode |= FMODE_WSPLIT_INITIALIZED;
6138 fptr->mode &= ~FMODE_WSPLIT;
6140 else {
6141 fptr->mode &= ~(FMODE_WSPLIT_INITIALIZED|FMODE_WSPLIT);
6145 return INT2NUM(retval);
6146 #else
6147 rb_notimplement();
6148 return Qnil; /* not reached */
6149 #endif
6154 * call-seq:
6155 * ios.ioctl(integer_cmd, arg) => integer
6157 * Provides a mechanism for issuing low-level commands to control or
6158 * query I/O devices. Arguments and results are platform dependent. If
6159 * <i>arg</i> is a number, its value is passed directly. If it is a
6160 * string, it is interpreted as a binary sequence of bytes. On Unix
6161 * platforms, see <code>ioctl(2)</code> for details. Not implemented on
6162 * all platforms.
6165 static VALUE
6166 rb_io_ioctl(int argc, VALUE *argv, VALUE io)
6168 VALUE req, arg;
6170 rb_scan_args(argc, argv, "11", &req, &arg);
6171 return rb_io_ctl(io, req, arg, 1);
6175 * call-seq:
6176 * ios.fcntl(integer_cmd, arg) => integer
6178 * Provides a mechanism for issuing low-level commands to control or
6179 * query file-oriented I/O streams. Arguments and results are platform
6180 * dependent. If <i>arg</i> is a number, its value is passed
6181 * directly. If it is a string, it is interpreted as a binary sequence
6182 * of bytes (<code>Array#pack</code> might be a useful way to build this
6183 * string). On Unix platforms, see <code>fcntl(2)</code> for details.
6184 * Not implemented on all platforms.
6187 static VALUE
6188 rb_io_fcntl(int argc, VALUE *argv, VALUE io)
6190 #ifdef HAVE_FCNTL
6191 VALUE req, arg;
6193 rb_scan_args(argc, argv, "11", &req, &arg);
6194 return rb_io_ctl(io, req, arg, 0);
6195 #else
6196 rb_notimplement();
6197 return Qnil; /* not reached */
6198 #endif
6202 * call-seq:
6203 * syscall(fixnum [, args...]) => integer
6205 * Calls the operating system function identified by _fixnum_,
6206 * passing in the arguments, which must be either +String+
6207 * objects, or +Integer+ objects that ultimately fit within
6208 * a native +long+. Up to nine parameters may be passed (14
6209 * on the Atari-ST). The function identified by _fixnum_ is system
6210 * dependent. On some Unix systems, the numbers may be obtained from a
6211 * header file called <code>syscall.h</code>.
6213 * syscall 4, 1, "hello\n", 6 # '4' is write(2) on our box
6215 * <em>produces:</em>
6217 * hello
6220 static VALUE
6221 rb_f_syscall(int argc, VALUE *argv)
6223 #if defined(HAVE_SYSCALL) && !defined(__CHECKER__)
6224 #ifdef atarist
6225 unsigned long arg[14]; /* yes, we really need that many ! */
6226 #else
6227 unsigned long arg[8];
6228 #endif
6229 int retval = -1;
6230 int i = 1;
6231 int items = argc - 1;
6233 /* This probably won't work on machines where sizeof(long) != sizeof(int)
6234 * or where sizeof(long) != sizeof(char*). But such machines will
6235 * not likely have syscall implemented either, so who cares?
6238 rb_secure(2);
6239 if (argc == 0)
6240 rb_raise(rb_eArgError, "too few arguments for syscall");
6241 if (argc > sizeof(arg) / sizeof(arg[0]))
6242 rb_raise(rb_eArgError, "too many arguments for syscall");
6243 arg[0] = NUM2LONG(argv[0]); argv++;
6244 while (items--) {
6245 VALUE v = rb_check_string_type(*argv);
6247 if (!NIL_P(v)) {
6248 StringValue(v);
6249 rb_str_modify(v);
6250 arg[i] = (unsigned long)StringValueCStr(v);
6252 else {
6253 arg[i] = (unsigned long)NUM2LONG(*argv);
6255 argv++;
6256 i++;
6258 TRAP_BEG;
6259 switch (argc) {
6260 case 1:
6261 retval = syscall(arg[0]);
6262 break;
6263 case 2:
6264 retval = syscall(arg[0],arg[1]);
6265 break;
6266 case 3:
6267 retval = syscall(arg[0],arg[1],arg[2]);
6268 break;
6269 case 4:
6270 retval = syscall(arg[0],arg[1],arg[2],arg[3]);
6271 break;
6272 case 5:
6273 retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4]);
6274 break;
6275 case 6:
6276 retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5]);
6277 break;
6278 case 7:
6279 retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6]);
6280 break;
6281 case 8:
6282 retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
6283 arg[7]);
6284 break;
6285 #ifdef atarist
6286 case 9:
6287 retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
6288 arg[7], arg[8]);
6289 break;
6290 case 10:
6291 retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
6292 arg[7], arg[8], arg[9]);
6293 break;
6294 case 11:
6295 retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
6296 arg[7], arg[8], arg[9], arg[10]);
6297 break;
6298 case 12:
6299 retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
6300 arg[7], arg[8], arg[9], arg[10], arg[11]);
6301 break;
6302 case 13:
6303 retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
6304 arg[7], arg[8], arg[9], arg[10], arg[11], arg[12]);
6305 break;
6306 case 14:
6307 retval = syscall(arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],
6308 arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13]);
6309 break;
6310 #endif /* atarist */
6312 TRAP_END;
6313 if (retval < 0) rb_sys_fail(0);
6314 return INT2NUM(retval);
6315 #else
6316 rb_notimplement();
6317 return Qnil; /* not reached */
6318 #endif
6321 static VALUE
6322 io_new_instance(VALUE args)
6324 return rb_class_new_instance(2, (VALUE*)args+1, *(VALUE*)args);
6327 static void
6328 io_encoding_set(rb_io_t *fptr, int argc, VALUE v1, VALUE v2)
6330 if (NIL_P(v2)) argc = 1;
6331 if (argc == 2) {
6332 fptr->enc2 = rb_to_encoding(v1);
6333 fptr->enc = rb_to_encoding(v2);
6335 else if (argc == 1) {
6336 if (NIL_P(v1)) {
6337 fptr->enc = 0;
6338 fptr->enc2 = 0;
6340 else {
6341 VALUE tmp = rb_check_string_type(v1);
6342 if (!NIL_P(tmp)) {
6343 mode_enc(fptr, StringValueCStr(tmp));
6345 else {
6346 fptr->enc = rb_to_encoding(v1);
6347 fptr->enc2 = 0;
6354 * call-seq:
6355 * IO.pipe -> [read_io, write_io]
6356 * IO.pipe(ext_enc) -> [read_io, write_io]
6357 * IO.pipe("ext_enc:int_enc") -> [read_io, write_io]
6358 * IO.pipe(ext_enc, int_enc) -> [read_io, write_io]
6360 * Creates a pair of pipe endpoints (connected to each other) and
6361 * returns them as a two-element array of <code>IO</code> objects:
6362 * <code>[</code> <i>read_io</i>, <i>write_io</i> <code>]</code>. Not
6363 * available on all platforms.
6365 * If an encoding (encoding name or encoding object) is specified as an optional argument,
6366 * read string from pipe is tagged with the encoding specified.
6367 * If the argument is a colon separated two encoding names "A:B",
6368 * the read string is converted from encoding A (external encoding)
6369 * to encoding B (internal encoding), then tagged with B.
6370 * If two optional arguments are specified, those must be
6371 * encoding objects or encoding names,
6372 * and the first one is the external encoding,
6373 * and the second one is the internal encoding.
6375 * In the example below, the two processes close the ends of the pipe
6376 * that they are not using. This is not just a cosmetic nicety. The
6377 * read end of a pipe will not generate an end of file condition if
6378 * there are any writers with the pipe still open. In the case of the
6379 * parent process, the <code>rd.read</code> will never return if it
6380 * does not first issue a <code>wr.close</code>.
6382 * rd, wr = IO.pipe
6384 * if fork
6385 * wr.close
6386 * puts "Parent got: <#{rd.read}>"
6387 * rd.close
6388 * Process.wait
6389 * else
6390 * rd.close
6391 * puts "Sending message to parent"
6392 * wr.write "Hi Dad"
6393 * wr.close
6394 * end
6396 * <em>produces:</em>
6398 * Sending message to parent
6399 * Parent got: <Hi Dad>
6402 static VALUE
6403 rb_io_s_pipe(int argc, VALUE *argv, VALUE klass)
6405 #ifdef __human68k__
6406 rb_notimplement();
6407 return Qnil; /* not reached */
6408 #else
6409 int pipes[2], state;
6410 VALUE r, w, args[3], v1, v2;
6411 rb_io_t *fptr;
6413 rb_scan_args(argc, argv, "02", &v1, &v2);
6414 if (rb_pipe(pipes) == -1)
6415 rb_sys_fail(0);
6417 args[0] = klass;
6418 args[1] = INT2NUM(pipes[0]);
6419 args[2] = INT2FIX(O_RDONLY);
6420 r = rb_protect(io_new_instance, (VALUE)args, &state);
6421 if (state) {
6422 close(pipes[0]);
6423 close(pipes[1]);
6424 rb_jump_tag(state);
6426 GetOpenFile(r, fptr);
6427 io_encoding_set(fptr, argc, v1, v2);
6428 args[1] = INT2NUM(pipes[1]);
6429 args[2] = INT2FIX(O_WRONLY);
6430 w = rb_protect(io_new_instance, (VALUE)args, &state);
6431 if (state) {
6432 close(pipes[1]);
6433 if (!NIL_P(r)) rb_io_close(r);
6434 rb_jump_tag(state);
6436 rb_io_synchronized(RFILE(w)->fptr);
6438 return rb_assoc_new(r, w);
6439 #endif
6442 struct foreach_arg {
6443 int argc;
6444 VALUE *argv;
6445 VALUE io;
6448 static void
6449 open_key_args(int argc, VALUE *argv, struct foreach_arg *arg)
6451 VALUE opt, v;
6453 FilePathValue(argv[0]);
6454 arg->io = 0;
6455 arg->argc = argc > 1 ? 1 : 0;
6456 arg->argv = argv + 1;
6457 if (argc == 1) {
6458 no_key:
6459 arg->io = rb_io_open(RSTRING_PTR(argv[0]), "r");
6460 return;
6462 opt = rb_check_convert_type(argv[argc-1], T_HASH, "Hash", "to_hash");
6463 if (NIL_P(opt)) goto no_key;
6464 if (argc > 2) arg->argc = 1;
6465 else arg->argc = 0;
6467 v = rb_hash_aref(opt, sym_open_args);
6468 if (!NIL_P(v)) {
6469 VALUE args;
6471 v = rb_convert_type(v, T_ARRAY, "Array", "to_ary");
6472 args = rb_ary_new2(RARRAY_LEN(v)+1);
6473 rb_ary_push(args, argv[0]);
6474 rb_ary_concat(args, v);
6475 MEMCPY(RARRAY_PTR(args)+1, RARRAY_PTR(v), VALUE, RARRAY_LEN(v));
6477 arg->io = rb_io_open_with_args(RARRAY_LEN(args), RARRAY_PTR(args));
6478 return;
6480 v = rb_hash_aref(opt, sym_mode);
6481 if (!NIL_P(v)) {
6482 arg->io = rb_io_open(RSTRING_PTR(argv[0]), StringValueCStr(v));
6484 else {
6485 arg->io = rb_io_open(RSTRING_PTR(argv[0]), "r");
6488 io_set_encoding(arg->io, opt);
6491 static VALUE
6492 io_s_foreach(struct foreach_arg *arg)
6494 VALUE str;
6496 while (!NIL_P(str = rb_io_gets_m(arg->argc, arg->argv, arg->io))) {
6497 rb_yield(str);
6499 return Qnil;
6503 * call-seq:
6504 * IO.foreach(name, sep=$/) {|line| block } => nil
6505 * IO.foreach(name, limit) {|line| block } => nil
6506 * IO.foreach(name, sep, limit) {|line| block } => nil
6508 * Executes the block for every line in the named I/O port, where lines
6509 * are separated by <em>sep</em>.
6511 * IO.foreach("testfile") {|x| print "GOT ", x }
6513 * <em>produces:</em>
6515 * GOT This is line one
6516 * GOT This is line two
6517 * GOT This is line three
6518 * GOT And so on...
6520 * If the last argument is a hash, it's the keyword argument to open.
6521 * See <code>IO.read</code> for detail.
6525 static VALUE
6526 rb_io_s_foreach(int argc, VALUE *argv, VALUE self)
6528 struct foreach_arg arg;
6530 rb_scan_args(argc, argv, "13", NULL, NULL, NULL, NULL);
6531 RETURN_ENUMERATOR(self, argc, argv);
6532 open_key_args(argc, argv, &arg);
6533 if (NIL_P(arg.io)) return Qnil;
6534 return rb_ensure(io_s_foreach, (VALUE)&arg, rb_io_close, arg.io);
6537 static VALUE
6538 io_s_readlines(struct foreach_arg *arg)
6540 return rb_io_readlines(arg->argc, arg->argv, arg->io);
6544 * call-seq:
6545 * IO.readlines(name, sep=$/) => array
6546 * IO.readlines(name, limit) => array
6547 * IO.readlines(name, sep, limit) => array
6549 * Reads the entire file specified by <i>name</i> as individual
6550 * lines, and returns those lines in an array. Lines are separated by
6551 * <i>sep</i>.
6553 * a = IO.readlines("testfile")
6554 * a[0] #=> "This is line one\n"
6556 * If the last argument is a hash, it's the keyword argument to open.
6557 * See <code>IO.read</code> for detail.
6561 static VALUE
6562 rb_io_s_readlines(int argc, VALUE *argv, VALUE io)
6564 struct foreach_arg arg;
6566 rb_scan_args(argc, argv, "13", NULL, NULL, NULL, NULL);
6567 open_key_args(argc, argv, &arg);
6568 if (NIL_P(arg.io)) return Qnil;
6569 return rb_ensure(io_s_readlines, (VALUE)&arg, rb_io_close, arg.io);
6572 static VALUE
6573 io_s_read(struct foreach_arg *arg)
6575 return io_read(arg->argc, arg->argv, arg->io);
6579 * call-seq:
6580 * IO.read(name, [length [, offset]] ) => string
6581 * IO.read(name, [length [, offset]], opt) => string
6583 * Opens the file, optionally seeks to the given offset, then returns
6584 * <i>length</i> bytes (defaulting to the rest of the file).
6585 * <code>read</code> ensures the file is closed before returning.
6587 * If the last argument is a hash, it specifies option for internal
6588 * open(). The key would be the following. open_args: is exclusive
6589 * to others.
6591 * encoding: string or encoding
6593 * specifies encoding of the read string. encoding will be ignored
6594 * if length is specified.
6596 * mode: string
6598 * specifies mode argument for open(). it should start with "r"
6599 * otherwise it would cause error.
6601 * open_args: array of strings
6603 * specifies arguments for open() as an array.
6605 * IO.read("testfile") #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n"
6606 * IO.read("testfile", 20) #=> "This is line one\nThi"
6607 * IO.read("testfile", 20, 10) #=> "ne one\nThis is line "
6610 static VALUE
6611 rb_io_s_read(int argc, VALUE *argv, VALUE io)
6613 VALUE offset;
6614 struct foreach_arg arg;
6616 rb_scan_args(argc, argv, "13", NULL, NULL, &offset, NULL);
6617 open_key_args(argc, argv, &arg);
6618 if (NIL_P(arg.io)) return Qnil;
6619 if (!NIL_P(offset)) {
6620 rb_io_binmode(arg.io);
6621 rb_io_seek(arg.io, offset, SEEK_SET);
6622 if (arg.argc == 2) arg.argc = 1;
6624 return rb_ensure(io_s_read, (VALUE)&arg, rb_io_close, arg.io);
6627 struct copy_stream_struct {
6628 VALUE src;
6629 VALUE dst;
6630 off_t copy_length; /* (off_t)-1 if not specified */
6631 off_t src_offset; /* (off_t)-1 if not specified */
6633 int src_fd;
6634 int dst_fd;
6635 int close_src;
6636 int close_dst;
6637 off_t total;
6638 const char *syserr;
6639 int error_no;
6640 const char *notimp;
6641 rb_fdset_t fds;
6642 rb_thread_t *th;
6645 static int
6646 copy_stream_wait_read(struct copy_stream_struct *stp)
6648 int ret;
6649 rb_fd_zero(&stp->fds);
6650 rb_fd_set(stp->src_fd, &stp->fds);
6651 ret = rb_fd_select(rb_fd_max(&stp->fds), &stp->fds, NULL, NULL, NULL);
6652 if (ret == -1) {
6653 stp->syserr = "select";
6654 stp->error_no = errno;
6655 return -1;
6657 return 0;
6660 static int
6661 copy_stream_wait_write(struct copy_stream_struct *stp)
6663 int ret;
6664 rb_fd_zero(&stp->fds);
6665 rb_fd_set(stp->dst_fd, &stp->fds);
6666 ret = rb_fd_select(rb_fd_max(&stp->fds), NULL, &stp->fds, NULL, NULL);
6667 if (ret == -1) {
6668 stp->syserr = "select";
6669 stp->error_no = errno;
6670 return -1;
6672 return 0;
6675 #ifdef HAVE_SENDFILE
6677 #ifdef __linux__
6678 #define USE_SENDFILE
6680 #ifdef HAVE_SYS_SENDFILE_H
6681 #include <sys/sendfile.h>
6682 #endif
6684 static ssize_t
6685 simple_sendfile(int out_fd, int in_fd, off_t *offset, size_t count)
6687 return sendfile(out_fd, in_fd, offset, count);
6690 #endif
6692 #endif
6694 #ifdef USE_SENDFILE
6695 static int
6696 copy_stream_sendfile(struct copy_stream_struct *stp)
6698 struct stat src_stat, dst_stat;
6699 ssize_t ss;
6700 int ret;
6702 off_t copy_length;
6703 off_t src_offset;
6704 int use_pread;
6706 ret = fstat(stp->src_fd, &src_stat);
6707 if (ret == -1) {
6708 stp->syserr = "fstat";
6709 stp->error_no = errno;
6710 return -1;
6712 if (!S_ISREG(src_stat.st_mode))
6713 return 0;
6715 ret = fstat(stp->dst_fd, &dst_stat);
6716 if (ret == -1) {
6717 stp->syserr = "fstat";
6718 stp->error_no = errno;
6719 return -1;
6721 if ((dst_stat.st_mode & S_IFMT) != S_IFSOCK)
6722 return 0;
6724 src_offset = stp->src_offset;
6725 use_pread = src_offset != (off_t)-1;
6727 copy_length = stp->copy_length;
6728 if (copy_length == (off_t)-1) {
6729 if (use_pread)
6730 copy_length = src_stat.st_size - src_offset;
6731 else {
6732 off_t cur = lseek(stp->src_fd, 0, SEEK_CUR);
6733 if (cur == (off_t)-1) {
6734 stp->syserr = "lseek";
6735 stp->error_no = errno;
6736 return -1;
6738 copy_length = src_stat.st_size - cur;
6742 retry_sendfile:
6743 if (use_pread) {
6744 ss = simple_sendfile(stp->dst_fd, stp->src_fd, &src_offset, copy_length);
6746 else {
6747 ss = simple_sendfile(stp->dst_fd, stp->src_fd, NULL, copy_length);
6749 if (0 < ss) {
6750 stp->total += ss;
6751 copy_length -= ss;
6752 if (0 < copy_length) {
6753 ss = -1;
6754 errno = EAGAIN;
6757 if (ss == -1) {
6758 switch (errno) {
6759 case EINVAL:
6760 #ifdef ENOSYS
6761 case ENOSYS:
6762 #endif
6763 return 0;
6764 case EAGAIN:
6765 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
6766 case EWOULDBLOCK:
6767 #endif
6768 if (copy_stream_wait_write(stp) == -1)
6769 return -1;
6770 if (RUBY_VM_INTERRUPTED(stp->th))
6771 return -1;
6772 goto retry_sendfile;
6774 stp->syserr = "sendfile";
6775 stp->error_no = errno;
6776 return -1;
6778 return 1;
6780 #endif
6782 static ssize_t
6783 copy_stream_read(struct copy_stream_struct *stp, char *buf, int len, off_t offset)
6785 ssize_t ss;
6786 retry_read:
6787 if (offset == (off_t)-1)
6788 ss = read(stp->src_fd, buf, len);
6789 else {
6790 #ifdef HAVE_PREAD
6791 ss = pread(stp->src_fd, buf, len, offset);
6792 #else
6793 stp->notimp = "pread";
6794 return -1;
6795 #endif
6797 if (ss == 0) {
6798 return 0;
6800 if (ss == -1) {
6801 switch (errno) {
6802 case EAGAIN:
6803 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
6804 case EWOULDBLOCK:
6805 #endif
6806 if (copy_stream_wait_read(stp) == -1)
6807 return -1;
6808 goto retry_read;
6809 #ifdef ENOSYS
6810 case ENOSYS:
6811 #endif
6812 stp->notimp = "pread";
6813 return -1;
6815 stp->syserr = offset == (off_t)-1 ? "read" : "pread";
6816 stp->error_no = errno;
6817 return -1;
6819 return ss;
6822 static int
6823 copy_stream_write(struct copy_stream_struct *stp, char *buf, int len)
6825 ssize_t ss;
6826 int off = 0;
6827 while (len) {
6828 ss = write(stp->dst_fd, buf+off, len);
6829 if (ss == -1) {
6830 if (errno == EAGAIN || errno == EWOULDBLOCK) {
6831 if (copy_stream_wait_write(stp) == -1)
6832 return -1;
6833 continue;
6835 stp->syserr = "write";
6836 stp->error_no = errno;
6837 return -1;
6839 off += ss;
6840 len -= ss;
6841 stp->total += ss;
6843 return 0;
6846 static void
6847 copy_stream_read_write(struct copy_stream_struct *stp)
6849 char buf[1024*16];
6850 int len;
6851 ssize_t ss;
6852 int ret;
6853 off_t copy_length;
6854 int use_eof;
6855 off_t src_offset;
6856 int use_pread;
6858 copy_length = stp->copy_length;
6859 use_eof = copy_length == (off_t)-1;
6860 src_offset = stp->src_offset;
6861 use_pread = src_offset != (off_t)-1;
6863 if (use_pread && stp->close_src) {
6864 off_t r;
6865 r = lseek(stp->src_fd, src_offset, SEEK_SET);
6866 if (r == (off_t)-1) {
6867 stp->syserr = "lseek";
6868 stp->error_no = errno;
6869 return;
6871 src_offset = (off_t)-1;
6872 use_pread = 0;
6875 while (use_eof || 0 < copy_length) {
6876 if (!use_eof && copy_length < sizeof(buf)) {
6877 len = copy_length;
6879 else {
6880 len = sizeof(buf);
6882 if (use_pread) {
6883 ss = copy_stream_read(stp, buf, len, src_offset);
6884 if (0 < ss)
6885 src_offset += ss;
6887 else {
6888 ss = copy_stream_read(stp, buf, len, (off_t)-1);
6890 if (ss <= 0) /* EOF or error */
6891 return;
6893 ret = copy_stream_write(stp, buf, ss);
6894 if (ret < 0)
6895 return;
6897 if (!use_eof)
6898 copy_length -= ss;
6900 if (RUBY_VM_INTERRUPTED(stp->th))
6901 return;
6905 static VALUE
6906 copy_stream_func(void *arg)
6908 struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
6909 #ifdef USE_SENDFILE
6910 int ret;
6911 #endif
6913 #ifdef USE_SENDFILE
6914 ret = copy_stream_sendfile(stp);
6915 if (ret != 0)
6916 goto finish; /* error or success */
6917 #endif
6919 copy_stream_read_write(stp);
6921 #ifdef USE_SENDFILE
6922 finish:
6923 #endif
6924 return Qnil;
6927 static VALUE
6928 copy_stream_fallback_body(VALUE arg)
6930 struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
6931 const int buflen = 16*1024;
6932 VALUE n;
6933 VALUE buf = rb_str_buf_new(buflen);
6934 long rest = stp->copy_length;
6935 off_t off = stp->src_offset;
6937 while (1) {
6938 long numwrote;
6939 long l;
6940 if (stp->copy_length == (off_t)-1) {
6941 l = buflen;
6943 else {
6944 if (rest == 0)
6945 break;
6946 l = buflen < rest ? buflen : rest;
6948 if (stp->src_fd == -1) {
6949 rb_funcall(stp->src, id_readpartial, 2, INT2FIX(l), buf);
6951 else {
6952 ssize_t ss;
6953 rb_thread_wait_fd(stp->src_fd);
6954 rb_str_resize(buf, buflen);
6955 ss = copy_stream_read(stp, RSTRING_PTR(buf), l, off);
6956 if (ss == -1)
6957 return Qnil;
6958 if (ss == 0)
6959 rb_eof_error();
6960 rb_str_resize(buf, ss);
6961 if (off != (off_t)-1)
6962 off += ss;
6964 n = rb_io_write(stp->dst, buf);
6965 numwrote = NUM2LONG(n);
6966 stp->total += numwrote;
6967 rest -= numwrote;
6970 return Qnil;
6973 static VALUE
6974 copy_stream_fallback(struct copy_stream_struct *stp)
6976 if (stp->src_fd == -1 && stp->src_offset != (off_t)-1) {
6977 rb_raise(rb_eArgError, "cannot specify src_offset for non-IO");
6979 rb_rescue2(copy_stream_fallback_body, (VALUE)stp,
6980 (VALUE (*) (ANYARGS))0, (VALUE)0,
6981 rb_eEOFError, (VALUE)0);
6982 return Qnil;
6985 static VALUE
6986 copy_stream_body(VALUE arg)
6988 struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
6989 VALUE src_io, dst_io;
6990 rb_io_t *src_fptr = 0, *dst_fptr = 0;
6991 int src_fd, dst_fd;
6993 stp->th = GET_THREAD();
6995 stp->total = 0;
6997 if (stp->src == argf ||
6998 !(TYPE(stp->src) == T_FILE ||
6999 rb_respond_to(stp->src, rb_intern("to_io")) ||
7000 TYPE(stp->src) == T_STRING ||
7001 rb_respond_to(stp->src, rb_intern("to_path")))) {
7002 src_fd = -1;
7004 else {
7005 src_io = rb_check_convert_type(stp->src, T_FILE, "IO", "to_io");
7006 if (NIL_P(src_io)) {
7007 VALUE args[2];
7008 int flags = O_RDONLY;
7009 #ifdef O_NOCTTY
7010 flags |= O_NOCTTY;
7011 #endif
7012 FilePathValue(stp->src);
7013 args[0] = stp->src;
7014 args[1] = INT2NUM(flags);
7015 src_io = rb_class_new_instance(2, args, rb_cFile);
7016 stp->src = src_io;
7017 stp->close_src = 1;
7019 GetOpenFile(src_io, src_fptr);
7020 rb_io_check_readable(src_fptr);
7021 src_fd = src_fptr->fd;
7023 stp->src_fd = src_fd;
7025 if (stp->dst == argf ||
7026 !(TYPE(stp->dst) == T_FILE ||
7027 rb_respond_to(stp->dst, rb_intern("to_io")) ||
7028 TYPE(stp->dst) == T_STRING ||
7029 rb_respond_to(stp->dst, rb_intern("to_path")))) {
7030 dst_fd = -1;
7032 else {
7033 dst_io = rb_check_convert_type(stp->dst, T_FILE, "IO", "to_io");
7034 if (NIL_P(dst_io)) {
7035 VALUE args[3];
7036 int flags = O_WRONLY|O_CREAT|O_TRUNC;
7037 #ifdef O_NOCTTY
7038 flags |= O_NOCTTY;
7039 #endif
7040 FilePathValue(stp->dst);
7041 args[0] = stp->dst;
7042 args[1] = INT2NUM(flags);
7043 args[2] = INT2FIX(0600);
7044 dst_io = rb_class_new_instance(3, args, rb_cFile);
7045 stp->dst = dst_io;
7046 stp->close_dst = 1;
7048 else {
7049 dst_io = GetWriteIO(dst_io);
7050 stp->dst = dst_io;
7052 GetOpenFile(dst_io, dst_fptr);
7053 rb_io_check_writable(dst_fptr);
7054 dst_fd = dst_fptr->fd;
7056 stp->dst_fd = dst_fd;
7058 if (stp->src_offset == (off_t)-1 && src_fptr && src_fptr->rbuf_len) {
7059 long len = src_fptr->rbuf_len;
7060 VALUE str;
7061 if (stp->copy_length != (off_t)-1 && stp->copy_length < len) {
7062 len = stp->copy_length;
7064 str = rb_str_buf_new(len);
7065 rb_str_resize(str,len);
7066 read_buffered_data(RSTRING_PTR(str), len, src_fptr);
7067 if (dst_fptr) /* IO or filename */
7068 io_fwrite(str, dst_fptr);
7069 else /* others such as StringIO */
7070 rb_io_write(stp->dst, str);
7071 stp->total += len;
7072 if (stp->copy_length != (off_t)-1)
7073 stp->copy_length -= len;
7076 if (dst_fptr && io_fflush(dst_fptr) < 0) {
7077 rb_raise(rb_eIOError, "flush failed");
7080 if (stp->copy_length == 0)
7081 return Qnil;
7083 if (src_fd == -1 || dst_fd == -1) {
7084 return copy_stream_fallback(stp);
7087 rb_fd_init(&stp->fds);
7088 rb_fd_set(src_fd, &stp->fds);
7089 rb_fd_set(dst_fd, &stp->fds);
7091 return rb_thread_blocking_region(copy_stream_func, (void*)stp, RB_UBF_DFL, 0);
7094 static VALUE
7095 copy_stream_finalize(VALUE arg)
7097 struct copy_stream_struct *stp = (struct copy_stream_struct *)arg;
7098 if (stp->close_src) {
7099 rb_io_close_m(stp->src);
7101 if (stp->close_dst) {
7102 rb_io_close_m(stp->dst);
7104 rb_fd_term(&stp->fds);
7105 if (stp->syserr) {
7106 errno = stp->error_no;
7107 rb_sys_fail(stp->syserr);
7109 if (stp->notimp) {
7110 rb_raise(rb_eNotImpError, "%s() not implemented", stp->notimp);
7112 return Qnil;
7116 * call-seq:
7117 * IO.copy_stream(src, dst)
7118 * IO.copy_stream(src, dst, copy_length)
7119 * IO.copy_stream(src, dst, copy_length, src_offset)
7121 * IO.copy_stream copies <i>src</i> to <i>dst</i>.
7122 * <i>src</i> and <i>dst</i> is either a filename or an IO.
7124 * This method returns the number of bytes copied.
7126 * If optional arguments are not given,
7127 * the start position of the copy is
7128 * the beginning of the filename or
7129 * the current file offset of the IO.
7130 * The end position of the copy is the end of file.
7132 * If <i>copy_length</i> is given,
7133 * No more than <i>copy_length</i> bytes are copied.
7135 * If <i>src_offset</i> is given,
7136 * it specifies the start position of the copy.
7138 * When <i>src_offset</i> is specified and
7139 * <i>src</i> is an IO,
7140 * IO.copy_stream doesn't move the current file offset.
7143 static VALUE
7144 rb_io_s_copy_stream(int argc, VALUE *argv, VALUE io)
7146 VALUE src, dst, length, src_offset;
7147 struct copy_stream_struct st;
7149 MEMZERO(&st, struct copy_stream_struct, 1);
7151 rb_scan_args(argc, argv, "22", &src, &dst, &length, &src_offset);
7153 st.src = src;
7154 st.dst = dst;
7156 if (NIL_P(length))
7157 st.copy_length = (off_t)-1;
7158 else
7159 st.copy_length = NUM2OFFT(length);
7161 if (NIL_P(src_offset))
7162 st.src_offset = (off_t)-1;
7163 else
7164 st.src_offset = NUM2OFFT(src_offset);
7166 rb_ensure(copy_stream_body, (VALUE)&st, copy_stream_finalize, (VALUE)&st);
7168 return OFFT2NUM(st.total);
7172 * call-seq:
7173 * io.external_encoding => encoding
7175 * Returns the Encoding object that represents the encoding of the file.
7176 * If io is write mode and no encoding is specified, returns <code>nil</code>.
7179 static VALUE
7180 rb_io_external_encoding(VALUE io)
7182 rb_io_t *fptr;
7184 GetOpenFile(io, fptr);
7185 if (fptr->enc2) {
7186 return rb_enc_from_encoding(fptr->enc2);
7188 if (!fptr->enc && fptr->fd == 0) {
7189 fptr->enc = rb_default_external_encoding();
7191 if (fptr->mode & FMODE_WRITABLE) {
7192 if (fptr->enc)
7193 return rb_enc_from_encoding(fptr->enc);
7194 return Qnil;
7196 return rb_enc_from_encoding(io_read_encoding(fptr));
7200 * call-seq:
7201 * io.internal_encoding => encoding
7203 * Returns the Encoding of the internal string if conversion is
7204 * specified. Otherwise returns nil.
7207 static VALUE
7208 rb_io_internal_encoding(VALUE io)
7210 rb_io_t *fptr;
7212 GetOpenFile(io, fptr);
7213 if (!fptr->enc2) return Qnil;
7214 return rb_enc_from_encoding(io_read_encoding(fptr));
7218 * call-seq:
7219 * io.set_encoding(ext_enc) => io
7220 * io.set_encoding("ext_enc:int_enc") => io
7221 * io.set_encoding(ext_enc, int_enc) => io
7223 * If single argument is specified, read string from io is tagged
7224 * with the encoding specified. If encoding is a colon separated two
7225 * encoding names "A:B", the read string is converted from encoding A
7226 * (external encoding) to encoding B (internal encoding), then tagged
7227 * with B. If two arguments are specified, those must be encoding
7228 * objects or encoding names, and the first one is the external encoding, and the
7229 * second one is the internal encoding.
7232 static VALUE
7233 rb_io_set_encoding(int argc, VALUE *argv, VALUE io)
7235 rb_io_t *fptr;
7236 VALUE v1, v2;
7238 rb_scan_args(argc, argv, "11", &v1, &v2);
7239 GetOpenFile(io, fptr);
7240 io_encoding_set(fptr, argc, v1, v2);
7241 return io;
7244 static VALUE
7245 argf_external_encoding(VALUE argf)
7247 if (!RTEST(current_file)) {
7248 return rb_enc_from_encoding(rb_default_external_encoding());
7250 return rb_io_external_encoding(rb_io_check_io(current_file));
7253 static VALUE
7254 argf_internal_encoding(VALUE argf)
7256 if (!RTEST(current_file)) {
7257 return rb_enc_from_encoding(rb_default_external_encoding());
7259 return rb_io_internal_encoding(rb_io_check_io(current_file));
7262 static VALUE
7263 argf_set_encoding(int argc, VALUE *argv, VALUE argf)
7265 rb_io_t *fptr;
7267 if (!next_argv()) {
7268 rb_raise(rb_eArgError, "no stream to set encoding");
7270 rb_io_set_encoding(argc, argv, current_file);
7271 GetOpenFile(current_file, fptr);
7272 argf_enc = fptr->enc;
7273 argf_enc2 = fptr->enc2;
7274 return argf;
7277 static VALUE
7278 argf_tell(VALUE argf)
7280 if (!next_argv()) {
7281 rb_raise(rb_eArgError, "no stream to tell");
7283 ARGF_FORWARD(0, 0);
7284 return rb_io_tell(current_file);
7287 static VALUE
7288 argf_seek_m(int argc, VALUE *argv, VALUE argf)
7290 if (!next_argv()) {
7291 rb_raise(rb_eArgError, "no stream to seek");
7293 ARGF_FORWARD(argc, argv);
7294 return rb_io_seek_m(argc, argv, current_file);
7297 static VALUE
7298 argf_set_pos(VALUE argf, VALUE offset)
7300 if (!next_argv()) {
7301 rb_raise(rb_eArgError, "no stream to set position");
7303 ARGF_FORWARD(1, &offset);
7304 return rb_io_set_pos(current_file, offset);
7307 static VALUE
7308 argf_rewind(VALUE argf)
7310 if (!next_argv()) {
7311 rb_raise(rb_eArgError, "no stream to rewind");
7313 ARGF_FORWARD(0, 0);
7314 return rb_io_rewind(current_file);
7317 static VALUE
7318 argf_fileno(VALUE argf)
7320 if (!next_argv()) {
7321 rb_raise(rb_eArgError, "no stream");
7323 ARGF_FORWARD(0, 0);
7324 return rb_io_fileno(current_file);
7327 static VALUE
7328 argf_to_io(VALUE argf)
7330 next_argv();
7331 ARGF_FORWARD(0, 0);
7332 return current_file;
7335 static VALUE
7336 argf_eof(VALUE argf)
7338 if (current_file) {
7339 if (init_p == 0) return Qtrue;
7340 ARGF_FORWARD(0, 0);
7341 if (rb_io_eof(current_file)) {
7342 return Qtrue;
7345 return Qfalse;
7348 static VALUE
7349 argf_read(int argc, VALUE *argv, VALUE argf)
7351 VALUE tmp, str, length;
7352 long len = 0;
7354 rb_scan_args(argc, argv, "02", &length, &str);
7355 if (!NIL_P(length)) {
7356 len = NUM2LONG(argv[0]);
7358 if (!NIL_P(str)) {
7359 StringValue(str);
7360 rb_str_resize(str,0);
7361 argv[1] = Qnil;
7364 retry:
7365 if (!next_argv()) {
7366 return str;
7368 if (ARGF_GENERIC_INPUT_P()) {
7369 tmp = argf_forward(argc, argv, argf);
7371 else {
7372 tmp = io_read(argc, argv, current_file);
7374 if (NIL_P(str)) str = tmp;
7375 else if (!NIL_P(tmp)) rb_str_append(str, tmp);
7376 if (NIL_P(tmp) || NIL_P(length)) {
7377 if (next_p != -1) {
7378 argf_close(current_file);
7379 next_p = 1;
7380 goto retry;
7383 else if (argc >= 1) {
7384 if (RSTRING_LEN(str) < len) {
7385 len -= RSTRING_LEN(str);
7386 argv[0] = INT2NUM(len);
7387 goto retry;
7390 return str;
7393 struct argf_call_arg {
7394 int argc;
7395 VALUE *argv;
7396 VALUE argf;
7399 static VALUE
7400 argf_forward_call(VALUE arg)
7402 struct argf_call_arg *p = (struct argf_call_arg *)arg;
7403 argf_forward(p->argc, p->argv, p->argf);
7404 return Qnil;
7407 static VALUE
7408 argf_readpartial(int argc, VALUE *argv, VALUE argf)
7410 VALUE tmp, str, length;
7412 rb_scan_args(argc, argv, "11", &length, &str);
7413 if (!NIL_P(str)) {
7414 StringValue(str);
7415 argv[1] = str;
7418 if (!next_argv()) {
7419 rb_str_resize(str, 0);
7420 rb_eof_error();
7422 if (ARGF_GENERIC_INPUT_P()) {
7423 struct argf_call_arg arg;
7424 arg.argc = argc;
7425 arg.argv = argv;
7426 arg.argf = argf;
7427 tmp = rb_rescue2(argf_forward_call, (VALUE)&arg,
7428 RUBY_METHOD_FUNC(0), Qnil, rb_eEOFError, (VALUE)0);
7430 else {
7431 tmp = io_getpartial(argc, argv, current_file, 0);
7433 if (NIL_P(tmp)) {
7434 if (next_p == -1) {
7435 rb_eof_error();
7437 argf_close(current_file);
7438 next_p = 1;
7439 if (RARRAY_LEN(rb_argv) == 0)
7440 rb_eof_error();
7441 if (NIL_P(str))
7442 str = rb_str_new(NULL, 0);
7443 return str;
7445 return tmp;
7448 static VALUE
7449 argf_getc(VALUE argf)
7451 VALUE ch;
7453 retry:
7454 if (!next_argv()) return Qnil;
7455 if (ARGF_GENERIC_INPUT_P()) {
7456 ch = rb_funcall3(current_file, rb_intern("getc"), 0, 0);
7458 else {
7459 ch = rb_io_getc(current_file);
7461 if (NIL_P(ch) && next_p != -1) {
7462 argf_close(current_file);
7463 next_p = 1;
7464 goto retry;
7467 return ch;
7470 static VALUE
7471 argf_getbyte(VALUE argf)
7473 VALUE ch;
7475 retry:
7476 if (!next_argv()) return Qnil;
7477 if (TYPE(current_file) != T_FILE) {
7478 ch = rb_funcall3(current_file, rb_intern("getbyte"), 0, 0);
7480 else {
7481 ch = rb_io_getbyte(current_file);
7483 if (NIL_P(ch) && next_p != -1) {
7484 argf_close(current_file);
7485 next_p = 1;
7486 goto retry;
7489 return ch;
7492 static VALUE
7493 argf_readchar(VALUE argf)
7495 VALUE ch;
7497 retry:
7498 if (!next_argv()) rb_eof_error();
7499 if (TYPE(current_file) != T_FILE) {
7500 ch = rb_funcall3(current_file, rb_intern("getc"), 0, 0);
7502 else {
7503 ch = rb_io_getc(current_file);
7505 if (NIL_P(ch) && next_p != -1) {
7506 argf_close(current_file);
7507 next_p = 1;
7508 goto retry;
7511 return ch;
7514 static VALUE
7515 argf_readbyte(VALUE argf)
7517 VALUE c;
7519 NEXT_ARGF_FORWARD(0, 0);
7520 c = argf_getbyte(argf);
7521 if (NIL_P(c)) {
7522 rb_eof_error();
7524 return c;
7527 static VALUE
7528 argf_each_line(int argc, VALUE *argv, VALUE argf)
7530 RETURN_ENUMERATOR(argf, argc, argv);
7531 for (;;) {
7532 if (!next_argv()) return Qnil;
7533 rb_block_call(current_file, rb_intern("each_line"), argc, argv, rb_yield, 0);
7534 next_p = 1;
7536 return argf;
7539 static VALUE
7540 argf_each_byte(VALUE argf)
7542 RETURN_ENUMERATOR(argf, 0, 0);
7543 for (;;) {
7544 if (!next_argv()) return Qnil;
7545 rb_block_call(current_file, rb_intern("each_byte"), 0, 0, rb_yield, 0);
7546 next_p = 1;
7550 static VALUE
7551 argf_each_char(VALUE argf)
7553 RETURN_ENUMERATOR(argf, 0, 0);
7554 for (;;) {
7555 if (!next_argv()) return Qnil;
7556 rb_block_call(current_file, rb_intern("each_char"), 0, 0, rb_yield, 0);
7557 next_p = 1;
7561 static VALUE
7562 argf_filename(VALUE argf)
7564 next_argv();
7565 return filename;
7568 static VALUE
7569 argf_filename_getter(ID id, VALUE *var)
7571 return argf_filename(*var);
7574 static VALUE
7575 argf_file(VALUE argf)
7577 next_argv();
7578 return current_file;
7581 static VALUE
7582 argf_binmode_m(VALUE argf)
7584 argf_binmode = 1;
7585 next_argv();
7586 ARGF_FORWARD(0, 0);
7587 rb_io_binmode(current_file);
7588 return argf;
7591 static VALUE
7592 argf_binmode_p(VALUE argf)
7594 return argf_binmode ? Qtrue : Qfalse;
7597 static VALUE
7598 argf_skip(VALUE argf)
7600 if (next_p != -1) {
7601 argf_close(current_file);
7602 next_p = 1;
7604 return argf;
7607 static VALUE
7608 argf_close_m(VALUE argf)
7610 next_argv();
7611 argf_close(current_file);
7612 if (next_p != -1) {
7613 next_p = 1;
7615 gets_lineno = 0;
7616 return argf;
7619 static VALUE
7620 argf_closed(VALUE argf)
7622 next_argv();
7623 ARGF_FORWARD(0, 0);
7624 return rb_io_closed(current_file);
7627 static VALUE
7628 argf_to_s(VALUE argf)
7630 return rb_str_new2("ARGF");
7633 static VALUE
7634 argf_inplace_mode_get(VALUE argf)
7636 if (!ruby_inplace_mode) return Qnil;
7637 return rb_str_new2(ruby_inplace_mode);
7640 static VALUE
7641 opt_i_get(ID id, VALUE *var)
7643 return argf_inplace_mode_get(*var);
7646 static VALUE
7647 argf_inplace_mode_set(VALUE argf, VALUE val)
7649 if (!RTEST(val)) {
7650 if (ruby_inplace_mode) free(ruby_inplace_mode);
7651 ruby_inplace_mode = 0;
7653 else {
7654 StringValue(val);
7655 if (ruby_inplace_mode) free(ruby_inplace_mode);
7656 ruby_inplace_mode = 0;
7657 ruby_inplace_mode = strdup(RSTRING_PTR(val));
7659 return argf;
7662 static void
7663 opt_i_set(VALUE val, ID id, VALUE *var)
7665 argf_inplace_mode_set(*var, val);
7668 const char *
7669 ruby_get_inplace_mode(void)
7671 return ruby_inplace_mode;
7674 void
7675 ruby_set_inplace_mode(const char *suffix)
7677 if (ruby_inplace_mode) free(ruby_inplace_mode);
7678 ruby_inplace_mode = 0;
7679 if (suffix) ruby_inplace_mode = strdup(suffix);
7682 static VALUE
7683 argf_argv(VALUE argf)
7685 return rb_argv;
7688 static VALUE
7689 argf_argv_getter(ID id, VALUE *var)
7691 return argf_argv(*var);
7694 VALUE
7695 rb_get_argv(void)
7697 return rb_argv;
7701 * Class <code>IO</code> is the basis for all input and output in Ruby.
7702 * An I/O stream may be <em>duplexed</em> (that is, bidirectional), and
7703 * so may use more than one native operating system stream.
7705 * Many of the examples in this section use class <code>File</code>,
7706 * the only standard subclass of <code>IO</code>. The two classes are
7707 * closely associated.
7709 * As used in this section, <em>portname</em> may take any of the
7710 * following forms.
7712 * * A plain string represents a filename suitable for the underlying
7713 * operating system.
7715 * * A string starting with ``<code>|</code>'' indicates a subprocess.
7716 * The remainder of the string following the ``<code>|</code>'' is
7717 * invoked as a process with appropriate input/output channels
7718 * connected to it.
7720 * * A string equal to ``<code>|-</code>'' will create another Ruby
7721 * instance as a subprocess.
7723 * Ruby will convert pathnames between different operating system
7724 * conventions if possible. For instance, on a Windows system the
7725 * filename ``<code>/gumby/ruby/test.rb</code>'' will be opened as
7726 * ``<code>\gumby\ruby\test.rb</code>''. When specifying a
7727 * Windows-style filename in a Ruby string, remember to escape the
7728 * backslashes:
7730 * "c:\\gumby\\ruby\\test.rb"
7732 * Our examples here will use the Unix-style forward slashes;
7733 * <code>File::SEPARATOR</code> can be used to get the
7734 * platform-specific separator character.
7736 * I/O ports may be opened in any one of several different modes, which
7737 * are shown in this section as <em>mode</em>. The mode may
7738 * either be a Fixnum or a String. If numeric, it should be
7739 * one of the operating system specific constants (O_RDONLY,
7740 * O_WRONLY, O_RDWR, O_APPEND and so on). See man open(2) for
7741 * more information.
7743 * If the mode is given as a String, it must be one of the
7744 * values listed in the following table.
7746 * Mode | Meaning
7747 * -----+--------------------------------------------------------
7748 * "r" | Read-only, starts at beginning of file (default mode).
7749 * -----+--------------------------------------------------------
7750 * "r+" | Read-write, starts at beginning of file.
7751 * -----+--------------------------------------------------------
7752 * "w" | Write-only, truncates existing file
7753 * | to zero length or creates a new file for writing.
7754 * -----+--------------------------------------------------------
7755 * "w+" | Read-write, truncates existing file to zero length
7756 * | or creates a new file for reading and writing.
7757 * -----+--------------------------------------------------------
7758 * "a" | Write-only, starts at end of file if file exists,
7759 * | otherwise creates a new file for writing.
7760 * -----+--------------------------------------------------------
7761 * "a+" | Read-write, starts at end of file if file exists,
7762 * | otherwise creates a new file for reading and
7763 * | writing.
7764 * -----+--------------------------------------------------------
7765 * "b" | (DOS/Windows only) Binary file mode (may appear with
7766 * | any of the key letters listed above).
7769 * The global constant ARGF (also accessible as $<) provides an
7770 * IO-like stream which allows access to all files mentioned on the
7771 * command line (or STDIN if no files are mentioned). ARGF provides
7772 * the methods <code>#path</code> and <code>#filename</code> to access
7773 * the name of the file currently being read.
7776 void
7777 Init_IO(void)
7779 #undef rb_intern
7780 #define rb_intern(str) rb_intern_const(str)
7782 VALUE rb_cARGF;
7783 #ifdef __CYGWIN__
7784 #include <sys/cygwin.h>
7785 static struct __cygwin_perfile pf[] =
7787 {"", O_RDONLY | O_BINARY},
7788 {"", O_WRONLY | O_BINARY},
7789 {"", O_RDWR | O_BINARY},
7790 {"", O_APPEND | O_BINARY},
7791 {NULL, 0}
7793 cygwin_internal(CW_PERFILE, pf);
7794 #endif
7796 rb_eIOError = rb_define_class("IOError", rb_eStandardError);
7797 rb_eEOFError = rb_define_class("EOFError", rb_eIOError);
7799 id_write = rb_intern("write");
7800 id_read = rb_intern("read");
7801 id_getc = rb_intern("getc");
7802 id_flush = rb_intern("flush");
7803 id_encode = rb_intern("encode");
7804 id_readpartial = rb_intern("readpartial");
7806 rb_define_global_function("syscall", rb_f_syscall, -1);
7808 rb_define_global_function("open", rb_f_open, -1);
7809 rb_define_global_function("printf", rb_f_printf, -1);
7810 rb_define_global_function("print", rb_f_print, -1);
7811 rb_define_global_function("putc", rb_f_putc, 1);
7812 rb_define_global_function("puts", rb_f_puts, -1);
7813 rb_define_global_function("gets", rb_f_gets, -1);
7814 rb_define_global_function("readline", rb_f_readline, -1);
7815 rb_define_global_function("select", rb_f_select, -1);
7817 rb_define_global_function("readlines", rb_f_readlines, -1);
7819 rb_define_global_function("`", rb_f_backquote, 1);
7821 rb_define_global_function("p", rb_f_p, -1);
7822 rb_define_method(rb_mKernel, "display", rb_obj_display, -1);
7824 rb_cIO = rb_define_class("IO", rb_cObject);
7825 rb_include_module(rb_cIO, rb_mEnumerable);
7827 rb_define_alloc_func(rb_cIO, io_alloc);
7828 rb_define_singleton_method(rb_cIO, "new", rb_io_s_new, -1);
7829 rb_define_singleton_method(rb_cIO, "open", rb_io_s_open, -1);
7830 rb_define_singleton_method(rb_cIO, "sysopen", rb_io_s_sysopen, -1);
7831 rb_define_singleton_method(rb_cIO, "for_fd", rb_io_s_for_fd, -1);
7832 rb_define_singleton_method(rb_cIO, "popen", rb_io_s_popen, -1);
7833 rb_define_singleton_method(rb_cIO, "foreach", rb_io_s_foreach, -1);
7834 rb_define_singleton_method(rb_cIO, "readlines", rb_io_s_readlines, -1);
7835 rb_define_singleton_method(rb_cIO, "read", rb_io_s_read, -1);
7836 rb_define_singleton_method(rb_cIO, "select", rb_f_select, -1);
7837 rb_define_singleton_method(rb_cIO, "pipe", rb_io_s_pipe, -1);
7838 rb_define_singleton_method(rb_cIO, "try_convert", rb_io_s_try_convert, 1);
7839 rb_define_singleton_method(rb_cIO, "copy_stream", rb_io_s_copy_stream, -1);
7841 rb_define_method(rb_cIO, "initialize", rb_io_initialize, -1);
7843 rb_output_fs = Qnil;
7844 rb_define_hooked_variable("$,", &rb_output_fs, 0, rb_str_setter);
7846 rb_global_variable(&rb_default_rs);
7847 rb_rs = rb_default_rs = rb_str_new2("\n");
7848 rb_output_rs = Qnil;
7849 OBJ_FREEZE(rb_default_rs); /* avoid modifying RS_default */
7850 rb_define_hooked_variable("$/", &rb_rs, 0, rb_str_setter);
7851 rb_define_hooked_variable("$-0", &rb_rs, 0, rb_str_setter);
7852 rb_define_hooked_variable("$\\", &rb_output_rs, 0, rb_str_setter);
7854 rb_define_virtual_variable("$_", rb_lastline_get, rb_lastline_set);
7856 rb_define_method(rb_cIO, "initialize_copy", rb_io_init_copy, 1);
7857 rb_define_method(rb_cIO, "reopen", rb_io_reopen, -1);
7859 rb_define_method(rb_cIO, "print", rb_io_print, -1);
7860 rb_define_method(rb_cIO, "putc", rb_io_putc, 1);
7861 rb_define_method(rb_cIO, "puts", rb_io_puts, -1);
7862 rb_define_method(rb_cIO, "printf", rb_io_printf, -1);
7864 rb_define_method(rb_cIO, "each", rb_io_each_line, -1);
7865 rb_define_method(rb_cIO, "each_line", rb_io_each_line, -1);
7866 rb_define_method(rb_cIO, "each_byte", rb_io_each_byte, 0);
7867 rb_define_method(rb_cIO, "each_char", rb_io_each_char, 0);
7868 rb_define_method(rb_cIO, "lines", rb_io_lines, -1);
7869 rb_define_method(rb_cIO, "bytes", rb_io_bytes, 0);
7870 rb_define_method(rb_cIO, "chars", rb_io_chars, 0);
7872 rb_define_method(rb_cIO, "syswrite", rb_io_syswrite, 1);
7873 rb_define_method(rb_cIO, "sysread", rb_io_sysread, -1);
7875 rb_define_method(rb_cIO, "fileno", rb_io_fileno, 0);
7876 rb_define_alias(rb_cIO, "to_i", "fileno");
7877 rb_define_method(rb_cIO, "to_io", rb_io_to_io, 0);
7879 rb_define_method(rb_cIO, "fsync", rb_io_fsync, 0);
7880 rb_define_method(rb_cIO, "sync", rb_io_sync, 0);
7881 rb_define_method(rb_cIO, "sync=", rb_io_set_sync, 1);
7883 rb_define_method(rb_cIO, "lineno", rb_io_lineno, 0);
7884 rb_define_method(rb_cIO, "lineno=", rb_io_set_lineno, 1);
7886 rb_define_method(rb_cIO, "readlines", rb_io_readlines, -1);
7888 rb_define_method(rb_cIO, "read_nonblock", io_read_nonblock, -1);
7889 rb_define_method(rb_cIO, "write_nonblock", rb_io_write_nonblock, 1);
7890 rb_define_method(rb_cIO, "readpartial", io_readpartial, -1);
7891 rb_define_method(rb_cIO, "read", io_read, -1);
7892 rb_define_method(rb_cIO, "write", io_write, 1);
7893 rb_define_method(rb_cIO, "gets", rb_io_gets_m, -1);
7894 rb_define_method(rb_cIO, "readline", rb_io_readline, -1);
7895 rb_define_method(rb_cIO, "getc", rb_io_getc, 0);
7896 rb_define_method(rb_cIO, "getbyte", rb_io_getbyte, 0);
7897 rb_define_method(rb_cIO, "readchar", rb_io_readchar, 0);
7898 rb_define_method(rb_cIO, "readbyte", rb_io_readbyte, 0);
7899 rb_define_method(rb_cIO, "ungetc",rb_io_ungetc, 1);
7900 rb_define_method(rb_cIO, "<<", rb_io_addstr, 1);
7901 rb_define_method(rb_cIO, "flush", rb_io_flush, 0);
7902 rb_define_method(rb_cIO, "tell", rb_io_tell, 0);
7903 rb_define_method(rb_cIO, "seek", rb_io_seek_m, -1);
7904 rb_define_const(rb_cIO, "SEEK_SET", INT2FIX(SEEK_SET));
7905 rb_define_const(rb_cIO, "SEEK_CUR", INT2FIX(SEEK_CUR));
7906 rb_define_const(rb_cIO, "SEEK_END", INT2FIX(SEEK_END));
7907 rb_define_method(rb_cIO, "rewind", rb_io_rewind, 0);
7908 rb_define_method(rb_cIO, "pos", rb_io_tell, 0);
7909 rb_define_method(rb_cIO, "pos=", rb_io_set_pos, 1);
7910 rb_define_method(rb_cIO, "eof", rb_io_eof, 0);
7911 rb_define_method(rb_cIO, "eof?", rb_io_eof, 0);
7913 rb_define_method(rb_cIO, "close_on_exec?", rb_io_close_on_exec_p, 0);
7914 rb_define_method(rb_cIO, "close_on_exec=", rb_io_set_close_on_exec, 1);
7916 rb_define_method(rb_cIO, "close", rb_io_close_m, 0);
7917 rb_define_method(rb_cIO, "closed?", rb_io_closed, 0);
7918 rb_define_method(rb_cIO, "close_read", rb_io_close_read, 0);
7919 rb_define_method(rb_cIO, "close_write", rb_io_close_write, 0);
7921 rb_define_method(rb_cIO, "isatty", rb_io_isatty, 0);
7922 rb_define_method(rb_cIO, "tty?", rb_io_isatty, 0);
7923 rb_define_method(rb_cIO, "binmode", rb_io_binmode_m, 0);
7924 rb_define_method(rb_cIO, "binmode?", rb_io_binmode_p, 0);
7925 rb_define_method(rb_cIO, "sysseek", rb_io_sysseek, -1);
7927 rb_define_method(rb_cIO, "ioctl", rb_io_ioctl, -1);
7928 rb_define_method(rb_cIO, "fcntl", rb_io_fcntl, -1);
7929 rb_define_method(rb_cIO, "pid", rb_io_pid, 0);
7930 rb_define_method(rb_cIO, "inspect", rb_io_inspect, 0);
7932 rb_define_method(rb_cIO, "external_encoding", rb_io_external_encoding, 0);
7933 rb_define_method(rb_cIO, "internal_encoding", rb_io_internal_encoding, 0);
7934 rb_define_method(rb_cIO, "set_encoding", rb_io_set_encoding, -1);
7936 rb_define_variable("$stdin", &rb_stdin);
7937 rb_stdin = prep_stdio(stdin, FMODE_READABLE, rb_cIO, "<STDIN>");
7938 rb_define_hooked_variable("$stdout", &rb_stdout, 0, stdout_setter);
7939 rb_stdout = prep_stdio(stdout, FMODE_WRITABLE, rb_cIO, "<STDOUT>");
7940 rb_define_hooked_variable("$stderr", &rb_stderr, 0, stdout_setter);
7941 rb_stderr = prep_stdio(stderr, FMODE_WRITABLE|FMODE_SYNC, rb_cIO, "<STDERR>");
7942 rb_define_hooked_variable("$>", &rb_stdout, 0, stdout_setter);
7943 orig_stdout = rb_stdout;
7944 rb_deferr = orig_stderr = rb_stderr;
7946 /* constants to hold original stdin/stdout/stderr */
7947 rb_define_global_const("STDIN", rb_stdin);
7948 rb_define_global_const("STDOUT", rb_stdout);
7949 rb_define_global_const("STDERR", rb_stderr);
7951 rb_cARGF = rb_class_new(rb_cObject);
7952 rb_set_class_path(rb_cARGF, rb_cObject, "ARGF.class");
7953 rb_define_alloc_func(rb_cARGF, argf_alloc);
7955 rb_include_module(rb_cARGF, rb_mEnumerable);
7957 rb_define_method(rb_cARGF, "initialize", argf_initialize, -2);
7958 rb_define_method(rb_cARGF, "initialize_copy", argf_initialize_copy, 1);
7959 rb_define_method(rb_cARGF, "to_s", argf_to_s, 0);
7960 rb_define_method(rb_cARGF, "argv", argf_argv, 0);
7962 rb_define_method(rb_cARGF, "fileno", argf_fileno, 0);
7963 rb_define_method(rb_cARGF, "to_i", argf_fileno, 0);
7964 rb_define_method(rb_cARGF, "to_io", argf_to_io, 0);
7965 rb_define_method(rb_cARGF, "each", argf_each_line, -1);
7966 rb_define_method(rb_cARGF, "each_line", argf_each_line, -1);
7967 rb_define_method(rb_cARGF, "each_byte", argf_each_byte, 0);
7968 rb_define_method(rb_cARGF, "each_char", argf_each_char, 0);
7969 rb_define_method(rb_cARGF, "lines", argf_each_line, -1);
7970 rb_define_method(rb_cARGF, "bytes", argf_each_byte, 0);
7971 rb_define_method(rb_cARGF, "chars", argf_each_char, 0);
7973 rb_define_method(rb_cARGF, "read", argf_read, -1);
7974 rb_define_method(rb_cARGF, "readpartial", argf_readpartial, -1);
7975 rb_define_method(rb_cARGF, "readlines", argf_readlines, -1);
7976 rb_define_method(rb_cARGF, "to_a", argf_readlines, -1);
7977 rb_define_method(rb_cARGF, "gets", argf_gets, -1);
7978 rb_define_method(rb_cARGF, "readline", argf_readline, -1);
7979 rb_define_method(rb_cARGF, "getc", argf_getc, 0);
7980 rb_define_method(rb_cARGF, "getbyte", argf_getbyte, 0);
7981 rb_define_method(rb_cARGF, "readchar", argf_readchar, 0);
7982 rb_define_method(rb_cARGF, "readbyte", argf_readbyte, 0);
7983 rb_define_method(rb_cARGF, "tell", argf_tell, 0);
7984 rb_define_method(rb_cARGF, "seek", argf_seek_m, -1);
7985 rb_define_method(rb_cARGF, "rewind", argf_rewind, 0);
7986 rb_define_method(rb_cARGF, "pos", argf_tell, 0);
7987 rb_define_method(rb_cARGF, "pos=", argf_set_pos, 1);
7988 rb_define_method(rb_cARGF, "eof", argf_eof, 0);
7989 rb_define_method(rb_cARGF, "eof?", argf_eof, 0);
7990 rb_define_method(rb_cARGF, "binmode", argf_binmode_m, 0);
7991 rb_define_method(rb_cARGF, "binmode?", argf_binmode_p, 0);
7993 rb_define_method(rb_cARGF, "filename", argf_filename, 0);
7994 rb_define_method(rb_cARGF, "path", argf_filename, 0);
7995 rb_define_method(rb_cARGF, "file", argf_file, 0);
7996 rb_define_method(rb_cARGF, "skip", argf_skip, 0);
7997 rb_define_method(rb_cARGF, "close", argf_close_m, 0);
7998 rb_define_method(rb_cARGF, "closed?", argf_closed, 0);
8000 rb_define_method(rb_cARGF, "lineno", argf_lineno, 0);
8001 rb_define_method(rb_cARGF, "lineno=", argf_set_lineno, 1);
8003 rb_define_method(rb_cARGF, "inplace_mode", argf_inplace_mode_get, 0);
8004 rb_define_method(rb_cARGF, "inplace_mode=", argf_inplace_mode_set, 1);
8006 rb_define_method(rb_cARGF, "external_encoding", argf_external_encoding, 0);
8007 rb_define_method(rb_cARGF, "internal_encoding", argf_internal_encoding, 0);
8008 rb_define_method(rb_cARGF, "set_encoding", argf_set_encoding, -1);
8010 argf = rb_class_new_instance(0, 0, rb_cARGF);
8012 rb_define_readonly_variable("$<", &argf);
8013 rb_define_global_const("ARGF", argf);
8015 rb_define_hooked_variable("$.", &argf, argf_lineno_getter, argf_lineno_setter);
8016 rb_define_hooked_variable("$FILENAME", &argf, argf_filename_getter, 0);
8017 filename = rb_str_new2("-");
8019 rb_define_hooked_variable("$-i", &argf, opt_i_get, opt_i_set);
8020 rb_define_hooked_variable("$*", &argf, argf_argv_getter, 0);
8022 #if defined (_WIN32) || defined(DJGPP) || defined(__CYGWIN__) || defined(__human68k__)
8023 atexit(pipe_atexit);
8024 #endif
8026 Init_File();
8028 rb_define_method(rb_cFile, "initialize", rb_file_initialize, -1);
8030 rb_file_const("RDONLY", INT2FIX(O_RDONLY));
8031 rb_file_const("WRONLY", INT2FIX(O_WRONLY));
8032 rb_file_const("RDWR", INT2FIX(O_RDWR));
8033 rb_file_const("APPEND", INT2FIX(O_APPEND));
8034 rb_file_const("CREAT", INT2FIX(O_CREAT));
8035 rb_file_const("EXCL", INT2FIX(O_EXCL));
8036 #if defined(O_NDELAY) || defined(O_NONBLOCK)
8037 # ifdef O_NONBLOCK
8038 rb_file_const("NONBLOCK", INT2FIX(O_NONBLOCK));
8039 # else
8040 rb_file_const("NONBLOCK", INT2FIX(O_NDELAY));
8041 # endif
8042 #endif
8043 rb_file_const("TRUNC", INT2FIX(O_TRUNC));
8044 #ifdef O_NOCTTY
8045 rb_file_const("NOCTTY", INT2FIX(O_NOCTTY));
8046 #endif
8047 #ifdef O_BINARY
8048 rb_file_const("BINARY", INT2FIX(O_BINARY));
8049 #else
8050 rb_file_const("BINARY", INT2FIX(0));
8051 #endif
8052 #ifdef O_SYNC
8053 rb_file_const("SYNC", INT2FIX(O_SYNC));
8054 #endif
8056 sym_mode = ID2SYM(rb_intern("mode"));
8057 sym_perm = ID2SYM(rb_intern("perm"));
8058 sym_extenc = ID2SYM(rb_intern("external_encoding"));
8059 sym_intenc = ID2SYM(rb_intern("internal_encoding"));
8060 sym_encoding = ID2SYM(rb_intern("encoding"));
8061 sym_open_args = ID2SYM(rb_intern("open_args"));