1. Computing

Using Temporary Files

By

Temporary files are files stored by a program that don't need any permanent filename. In other words, the program needs to store some data, perhaps to be shared between other programs, but the name of the file is irrelevant and the file will be short-lived. At the very minimum, the file will be deleted when the computer is rebooted, or periodically.

Every operating system has its own way of dealing with temporary files. On Linux and UNIX-like systems, there are directories like /tmp and /var/tmp that you can store temporary files in. However, there's slightly more to it than that. Without doing some checks at to whether you can actually create and write to files in these directories, you might not be able to tell whether this really is the directory you should be using. You might also be restricted by kernel-level security programs like SELinux or a chroot. Finally, if your program is run on another platform (Windows, for example), that directory won't make any sense.

Another issue to consider is a name conflict or race condition. If your programs chooses its own name (for example, /tmp/my_tempfile), another program may also choose this name or a second instance of the program will choose the same filename. These types of errors, those that arise from interactions between different programs, are notoriously difficult to track down. However, Ruby's Tempfile class solves all these problems.

The Tempfile Class

The Tempfile class is very simple to use. Simply pass a basename to the new or open methods and you're off. These methods return a File object you can use like any other File object.

When Tempfile objects are finalized (when no variables refer to them and the garbage collector deletes them), the temp files they refer to are unlinked from the filesystem. This ensures that programs don't leave temp files dangling every time the program is run, polluting the filesystem.

If the path of a Tempfile object must be shared between two processes or programs, it can be retrieved using the path method of a Tempfile object. Note that if that Tempfile object gets finalized it will be unlinked, so be sure to keep the object around as long as you need the file.

The following example demonstrates how to use the Tempfile class.

 #!/usr/bin/env ruby
 require 'tempfile'
 
 # Short-term use
 Tempfile.open('my_program') do|f|
   puts "Tempfile opened at #{f.path}"
   f.puts "Putting some text into the file"
 end
 
 # Long-term use
 tf = Tempfile.open('my_program')
 puts "Tempfile opened at #{tf.path}"
 tf.puts "Some data"
 
 # Later on in the program
 tf.rewind
 puts tf.gets
 
 # You can either close the Tempfile, or just
 # let it happen when the value gets finalized
 tf.close!
 
  1. About.com
  2. Computing
  3. Ruby
  4. Beginning Ruby
  5. Files and Directories
  6. Using Temporary Files

©2014 About.com. All rights reserved.