Method: IO#pread
- Defined in:
- io.c
#pread(maxlen, offset[, outbuf]) ⇒ String
Reads maxlen bytes from ios using the pread system call and returns them as a string without modifying the underlying descriptor offset. This is advantageous compared to combining IO#seek and IO#read in that it is atomic, allowing multiple threads/process to share the same IO object for reading the file at various locations. This bypasses any userspace buffering of the IO layer. If the optional outbuf argument is present, it must reference a String, which will receive the data. Raises SystemCallError on error, EOFError at end of file and NotImplementedError if platform does not implement the system call.
File.write("testfile", "This is line one\nThis is line two\n")
File.open("testfile") do |f|
p f.read # => "This is line one\nThis is line two\n"
p f.pread(12, 0) # => "This is line"
p f.pread(9, 8) # => "line one\n"
end
5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 |
# File 'io.c', line 5342
static VALUE
rb_io_pread(int argc, VALUE *argv, VALUE io)
{
VALUE len, offset, str;
rb_io_t *fptr;
ssize_t n;
struct prdwr_internal_arg arg;
int shrinkable;
rb_scan_args(argc, argv, "21", &len, &offset, &str);
arg.count = NUM2SIZET(len);
arg.offset = NUM2OFFT(offset);
shrinkable = io_setstrbuf(&str, (long)arg.count);
if (arg.count == 0) return str;
arg.buf = RSTRING_PTR(str);
GetOpenFile(io, fptr);
rb_io_check_byte_readable(fptr);
arg.fd = fptr->fd;
rb_io_check_closed(fptr);
rb_str_locktmp(str);
n = (ssize_t)rb_ensure(pread_internal_call, (VALUE)&arg, rb_str_unlocktmp, str);
if (n < 0) {
rb_sys_fail_path(fptr->pathv);
}
io_set_read_length(str, n, shrinkable);
if (n == 0 && arg.count > 0) {
rb_eof_error();
}
return str;
}
|