ungetc(p1)
public
Pushes back one character (passed as a parameter) onto ios, such
that a subsequent buffered read will return it.
Only one character may be pushed back before a subsequent read operation (that is, you will be able to read only the last of several characters that have
been pushed back). Has no effect with unbuffered reads (such as
IO#sysread).
f = File.new("testfile")
c = f.getc
f.ungetc(c)
f.getc
Show source
VALUE
rb_io_ungetc(VALUE io, VALUE c)
{
rb_io_t *fptr;
long len;
GetOpenFile(io, fptr);
rb_io_check_readable(fptr);
io_unset_eof(fptr);
if (NIL_P(c)) return Qnil;
if (FIXNUM_P(c)) {
int cc = FIX2INT(c);
rb_encoding *enc = io_read_encoding(fptr);
char buf[16];
c = rb_str_new(buf, rb_enc_mbcput(cc, buf, enc));
}
else {
SafeStringValue(c);
}
if (NEED_READCONV(fptr)) {
len = RSTRING_LEN(c);
make_readconv(fptr, len);
if (fptr->cbuf_capa - fptr->cbuf_len < len)
rb_raise(rb_eIOError, "ungetc failed");
if (fptr->cbuf_off < len) {
MEMMOVE(fptr->cbuf+fptr->cbuf_capa-fptr->cbuf_len,
fptr->cbuf+fptr->cbuf_off,
char, fptr->cbuf_len);
fptr->cbuf_off = fptr->cbuf_capa-fptr->cbuf_len;
}
fptr->cbuf_off -= len;
fptr->cbuf_len += len;
MEMMOVE(fptr->cbuf+fptr->cbuf_off, RSTRING_PTR(c), char, len);
}
else {
io_ungetbyte(c, fptr);
}
return Qnil;
}