End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
File#truncate
file.truncate(integer) → 0
file.c
View on GitHub ↗
static VALUE
rb_file_truncate(VALUE obj, VALUE len)
{
rb_io_t *fptr;
struct ftruncate_arg fa;
fa.pos = NUM2POS(len);
GetOpenFile(obj, fptr);
if (!(fptr->mode & FMODE_WRITABLE)) {
rb_raise(rb_eIOError, "not opened for writing");
}
rb_io_flush_raw(obj, 0);
fa.fd = fptr->fd;
if ((int)rb_thread_io_blocking_region(nogvl_ftruncate, &fa, fa.fd) < 0) {
rb_sys_fail_path(fptr->pathv);
}
return INT2FIX(0);
#undef NUM2POS
}
Truncates file to at most integer bytes. The file must be opened for writing. Not available on all platforms.
Example
f = File.new("out", "w") f.syswrite("1234567890") #=> 10 f.truncate(5) #=> 0 f.close() #=> nil File.size("out") #=> 5