Ruby File Input and Output

Ruby provides a complete set of I/O-related methods, implemented in the Kernel module. All I/O methods are derived from the IO class.

ClassIOProvides all the basic methods, such asread、 write、 gets、 puts、 readline、 getcandprintf。

This chapter will explain all the basic I/O functions available in Ruby. For more functions, please refer to Ruby'sIOclass.

putsStatement

In the previous chapters, you assigned values to variables and then used theputsstatement to print output.

putsThe statement instructs the program to display the value stored in the variable. This adds a newline at the end of each line.

Example

#!/usr/bin/ruby val1 = "This is variable one" val2 = "This is variable two" puts val1 puts val2

The output of the above example is:

This is variable one
This is variable two

getsStatement

getsThe statement can be used to obtain user input from the standard input named STDIN.

Example

The following code demonstrates how to use the gets statement. This code prompts the user to enter a value, the value will be stored in the variable val, and finally printed to STDOUT.

Example

#!/usr/bin/ruby puts "Enter a value :" val = gets puts val

The output of the above example is:

Enter a value :
This is entered value
This is entered value

putcStatement

andputsUnlike the statement,putsthe statement outputs the entire string to the screen, whileputcthe statement can be used to output one character at a time.

Example

The output of the following code is just the character H:

Example

#!/usr/bin/ruby str="Hello Ruby!" putc str

The output of the above example is:

H

printStatement

printThe statement is similar to theputsstatement. The only difference is thatputsthe statement jumps to the next line after outputting content, while using theprintstatement, the cursor is positioned on the same line.

Example

#!/usr/bin/ruby print "Hello World" print "Good Morning"

The output of the above example is:

Hello WorldGood Morning

Opening and Closing Files

So far, you have read from and written to standard input and output. Now, we will see how to operate on actual data files.

File.newMethod

You can use theFile.newmethod to create aFileobject for reading, writing, or both, depending on the mode parameter. Finally, you can use theFile.closemethod to close the file.

Syntax

aFile = File.new("filename", "mode") #... process the file aFile.close

File.openMethod

You can use theFile.openmethod to create a new file object and assign that file object to a file. However,File.openandFile.newthere is a slight difference between the methods. The difference is thatFile.openthe method can be associated with a block, whereasFile.newthe method cannot.

File.open("filename", "mode") do |aFile| # ... process the file end

The following table lists the different modes for opening files:

ModeDescription
rRead-only mode. The file pointer is placed at the beginning of the file. This is the default mode.
r+Read-write mode. The file pointer is placed at the beginning of the file.
wWrite-only mode. If the file exists, it overwrites the file. If the file does not exist, a new file is created for writing.
w+Read-write mode. If the file exists, it overwrites the existing file. If the file does not exist, a new file is created for reading and writing.
aWrite-only mode. If the file exists, the file pointer is placed at the end of the file. That is, the file is in append mode. If the file does not exist, a new file is created for writing.
a+Read-write mode. If the file exists, the file pointer is placed at the end of the file. That is, the file is in append mode. If the file does not exist, a new file is created for reading and writing.

Reading and Writing Files

Methods used for simple I/O can also be used with all file objects. So, gets reads a line from standard input,aFile.getsand reads a line from the file object aFile.

However, I/O objects provide additional settings for access methods, which brings us convenience.

sysreadMethod

You can use the methodsysreadto read the contents of a file. When using the sysread method, you can open the file in any mode. For example:

The following is the input text file:

This is a simple text file for testing purpose.

Now let us try to read this file:

Example

#!/usr/bin/ruby aFile = File.new("input.txt", "r") if aFile content = aFile.sysread(20) puts content else puts "Unable to open file!" end

This statement reads the first 20 characters of the input file. The file pointer will be placed at the position of the 21st character in the file.

syswriteMethod

You can use the methodsyswriteto write content to a file. When using the syswrite method, you need to open the file in write mode. For example:

Example

#!/usr/bin/ruby aFile = File.new("input.txt", "r+") if aFile aFile.syswrite("ABCDEF") else puts "Unable to open file!" end

This statement will write "ABCDEF" to the file.

each_byteMethod

This method belongs to the classFile. The methodeach_byteis an iterator that iterates over each character in a string. Look at the following code example:

Example

#!/usr/bin/ruby aFile = File.new("input.txt", "r+") if aFile aFile.syswrite("ABCDEF") aFile.rewind aFile.each_byte {|ch| putc ch; putc ?. } else puts "Unable to open file!" end

The characters are passed one by one to the variable ch, and then displayed on the screen, as shown below:

A.B.C.D.E.F.s. .a. .s.i.m.p.l.e. .t.e.x.t. .f.i.l.e. .f.o.r. .t.e.s.t.i.n.g. .p.u.r.p.o.s.e...

IO.readlinesMethod

ClassFileis a subclass of the IO class. The IO class also has some methods for manipulating files.

IO.readlinesis a method in the IO class. This method returns the contents of the file line by line. The following code shows the methodIO.readlinesusage:

Example

#!/usr/bin/ruby arr = IO.readlines("input.txt") puts arr[0] puts arr[1]

In this code, the variable arr is an array. The fileinput.txthas each line as an element in the array arr. Therefore, arr

IO.foreachMethod

This method also returns output line by line. The methodforeachand the methodreadlinesdiffer in that the methodforeachis associated with a block. However, unlike the methodreadlines, the methodforeachdoes not return an array. For example:

Example

#!/usr/bin/ruby IO.foreach("input.txt"){|block| puts block}

This code will pass the file'stestcontent line by line to the variable block, and then the output will be displayed on the screen.

Renaming and Deleting Files

You can use therenameanddeletemethod to rename and delete files.

The following example renames an existing filetest1.txt:

Example

#!/usr/bin/ruby #Rename file test1.txt to test2.txt File.rename( "test1.txt", "test2.txt" )

The following example deletes an existing filetest2.txt:

Example

#!/usr/bin/ruby #Delete file test2.txt File.delete("text2.txt")

File Modes and Ownership

Using thechmodmethod with a mask to change the mode or permission/access list of a file:

The following example changes the mode of an existing filetest.txtto a mask value:

Example

#!/usr/bin/ruby file = File.new( "test.txt", "w" ) file.chmod( 0755 )

The following table lists thechmoddifferent masks that can be used in the method:

MaskDescription
0700rwx mask for the owner
0400r, for the owner
0200w, for the owner
0100x, for the owner
0070rwx mask for the group
0040r, for the group
0020w, for the group
0010x, for the group
0007rwx mask for others
0004r, for others
0002w, for others
0001x, for others
4000Set user ID on execution
2000Set group ID on execution
1000Save swapped text, even after use

File Queries

The following command checks whether the file exists before opening the file:

Example

#!/usr/bin/ruby File.open("file.rb") if File::exists?( "file.rb" )

The following command checks whether the file is indeed a file:

Example

#!/usr/bin/ruby #Returns true or false. File.file?( "text.txt" )

The following command checks whether the given file name is a directory:

Example

#!/usr/bin/ruby #A directory File::directory?( "/usr/local/bin" ) # => true #A file File::directory?( "file.rb" ) # => false

The following command checks whether the file is readable, writable, and executable:

Example

#!/usr/bin/ruby File.readable?( "test.txt" ) # => true File.writable?( "test.txt" ) # => true File.executable?( "test.txt" ) # => false

The following command checks whether the file size is zero:

Example

#!/usr/bin/ruby File.zero?( "test.txt" ) # => true

The following command returns the size of the file:

Example

#!/usr/bin/ruby File.size?( "text.txt" ) # => 1002

The following command is used to check the type of the file:

Example

#!/usr/bin/ruby File::ftype( "test.txt" ) # => file

The ftype method identifies the type of the file by returning one of the following values:file, directory, characterSpecial, blockSpecial, fifo, link, socket, or unknown。

The following command is used to check the time the file was created, modified, or last accessed:

Example

#!/usr/bin/ruby File::ctime( "test.txt" ) # => Fri May 09 10:06:37 -0700 2008 File::mtime( "text.txt" ) # => Fri May 09 10:44:44 -0700 2008 File::atime( "text.txt" ) # => Fri May 09 10:45:01 -0700 2008

Directories in Ruby

All files are contained in directories, and Ruby provides ways to handle files and directories.FileThe File class is used to handle files,Dirand the Dir class is used to handle directories.

Browsing Directories

To change directories in a Ruby program, useDir.chdir. The following example changes the current directory to/usr/bin。

Dir.chdir("/usr/bin")

You can use Dir.pwdto view the current directory:

puts Dir.pwd #Returns the current directory, similar to /usr/bin

You can useDir.entriesto get the list of files and directories in the specified directory:

puts Dir.entries("/usr/bin").join(' ')

Dir.entriesReturns an array containing all items in the specified directory.Dir.foreachProvides the same functionality:

Dir.foreach("/usr/bin") do |entry| puts entry end

A more concise way to obtain a directory listing is to use Dir's array-like methods:

Dir["/usr/bin/*"]

Creating Directories

Dir.mkdirCan be used to create directories:

Dir.mkdir("mynewdir")

You can also set permissions on a new directory (not an existing directory) via mkdir:

Note:Mask 755 sets the permissions for owner, group, and world (anyone) to rwxr-xr-x, where r = read, w = write, x = execute.

Dir.mkdir( "mynewdir", 755 )

Deleting Directories

Dir.deleteCan be used to delete a directory.Dir.unlinkandDir.rmdirPerforms the same function, providing us with convenience.

Dir.delete("testdir")

Creating Files & Temporary Directories

Temporary files are information that is simply created during program execution but is not stored permanently.

Dir.tmpdirprovides the path to the temporary directory on the current system, but this method is not available by default. To makeDir.tmpdiravailable, it is necessary to require 'tmpdir'.

You can useDir.tmpdirandFile.jointogether to create a platform-independent temporary file:

require 'tmpdir' tempfilename = File.join(Dir.tmpdir, "tingtong") tempfile = File.new(tempfilename, "w") tempfile.puts "This is a temporary file" tempfile.close File.delete(tempfilename)

This code creates a temporary file, writes data to it, and then deletes the file. Ruby's standard library also includes a library namedTempfilelibrary, which can be used to create temporary files:

require 'tempfile' f = Tempfile.new('tingtong') f.puts "Hello" puts f.path f.close

Built-in Functions

The following provides a complete list of built-in functions for handling files and directories in Ruby:

Other Extensions