public Method

File.truncate(p1)

file.truncate(integer)     0

Truncates file to at most integer bytes. The file must be opened for writing. Not available on all platforms.

f = File.new("out", "w")
f.syswrite("1234567890")   #=> 10
f.truncate(5)              #=> 0
f.close()                  #=> nil
File.size("out")           #=> 5

Source Code

/*
*  call-seq:
*     file.truncate(integer)    => 0
*  
*  Truncates <i>file</i> to at most <i>integer</i> bytes. The file
*  must be opened for writing. Not available on all platforms.
*     
*     f = File.new("out", "w")
*     f.syswrite("1234567890")   #=> 10
*     f.truncate(5)              #=> 0
*     f.close()                  #=> nil
*     File.size("out")           #=> 5
*/

static VALUE
rb_file_truncate(obj, len)
   VALUE obj, len;
{
   OpenFile *fptr;
   FILE *f;
   off_t pos;

   rb_secure(2);
   pos = NUM2OFFT(len);
   GetOpenFile(obj, fptr);
   if (!(fptr->mode & FMODE_WRITABLE)) {
       rb_raise(rb_eIOError, "not opened for writing");
   }
   f = GetWriteFile(fptr);
   fflush(f);
   fseeko(f, (off_t)0, SEEK_CUR);
#ifdef HAVE_TRUNCATE
   if (ftruncate(fileno(f), pos) < 0)
       rb_sys_fail(fptr->path);
#else
# ifdef HAVE_CHSIZE
   if (chsize(fileno(f), pos) < 0)
       rb_sys_fail(fptr->path);
# else
   rb_notimplement();
# endif
#endif
   return INT2FIX(0);
}
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.