Truncating a File


You want to truncate a file to a certain length, probably zero bytes.


Usually, you want to destroy the old contents of a file and start over. Opening a file for write access will automatically truncate it to zero bytes, and let you write new contents to the file:

	filename = 'truncate.txt'
	open(filename, 'w') { |f| f << "All of this will be truncated." }
	File.size(filename) # => 30
	f = open(filename, 'w') {}
	File.size(filename) # => 0

If you just need to truncate the file to zero byt es, and not write any new contents to it, you can open it with an access mode of File::TRUNC.

	open(filename, 'w') { |f| f << "Here are some new contents." }
	File.size(filename) # => 27
	f = open(filename, File::TRUNC) {}
	File.size(filename) # => 0

You can't actually do anything with a FILE whose access mode is File::TRUNC:

	open(filename, File::TRUNC) do |f|
	 f << "At last, an empty file to write to!"
	# IOError: not opened for writing



Transient files are the most likely candidates for truncation. Log files are often truncated, automatically or by hand, before they grow too large.

The most common type of truncation is truncating a file to zero bytes, but the File.truncate method can truncate a file to any number of bytes, not just zero. You can also use the instance method, File#truncate, to truncate a file you've opened for writing:

	f = open(filename, 'w') do |f|
	 f << 'These words will remain intact after the file is truncated.'
	File.size(filename) # => 59
	File.truncate(filename, 30)
	File.size(filename) # => 30
	open(filename) { |f| } # => "These words will remain intact"

These methods don't always make a file smaller. If the file starts out smaller than the size you give, they append zero-bytes (00) to the end of file until the file reaches the specified size.

	f = open(filename, "w") { |f| f << "Brevity is the soul of wit." }
	File.size(filename) # => 27
	File.truncate(filename, 30)
	File.size(filename) # => 30
	open(filename) { |f| }
	# => "Brevity is the soul of wit.000000"

File.truncate and File#truncate act like the bed of Procrustes: they force a file to be a certain number of bytes long, whether that means stretching it or chopping off the end.



Date and Time



Files and Directories

Code Blocks and Iteration

Objects and Classes8

Modules and Namespaces

Reflection and Metaprogramming


Graphics and Other File Formats

Databases and Persistence

Internet Services

Web Development Ruby on Rails

Web Services and Distributed Programming

Testing, Debugging, Optimizing, and Documenting

Packaging and Distributing Software

Automating Tasks with Rake

Multitasking and Multithreading

User Interface

Extending Ruby with Other Languages

System Administration

Ruby Cookbook
Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399 © 2008-2020.
If you may any questions please contact us: