Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
class method
File.truncate
(::path file_name, ::int length) -> 0
File.truncate(filepath, size) → 0
file.c
View on GitHub ↗
static VALUE
rb_file_s_truncate(VALUE klass, VALUE path, VALUE len)
{
struct truncate_arg ta;
int r;
ta.pos = NUM2OFFT(len);
FilePathValue(path);
path = rb_str_encode_ospath(path);
ta.path = StringValueCStr(path);
r = IO_WITHOUT_GVL_INT(nogvl_truncate, &ta);
if (r < 0)
rb_sys_fail_path(path);
return INT2FIX(0);
}
Adjusts the size of file filepath to the given size:
Example
filepath = '/tmp/t.tmp' File.write(filepath, '0123456789') File.read(filepath) # => "0123456789" File.truncate(filepath, 5) File.read(filepath) # => "01234"
Pads with null characters if necessary:
Example
File.truncate(filepath, 10) File.read(filepath) # => "01234\u0000\u0000\u0000\u0000\u0000" File.delete(filepath) # Clean up.