Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Ruby File Input & Output

Ruby File Input & Output

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

class IO Provides all the basic methods, such as read、 write、 gets、 puts、 readline、 getc and printf。

This chapter will explain all the basic I/O functions available in Ruby. To learn more functions, see Ruby's IO class.

puts Statement

In previous chapters, you assigned values to variables and then used puts statements to print output.

puts statements instruct the program to display the value stored in a variable. This adds a new line 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 above example produces the following output:


This is variable one
This is variable two

gets Statement

gets statements can be used to get user input from the standard screen called STDIN.

Example

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

Example

!/usr/bin/ruby

puts

"

Enter a value :

"

val

=

gets

puts

val

The above example produces the following output:


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

putc Statement

The difference between puts statements,puts statements output an entire string to the screen, while putc statements 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 above example produces the following output:


H

print Statement

print The statement is used together with puts statements. The only difference is that puts statements move to the next line after outputting content, while using print statements leaves the cursor on the same line.

Example

!/usr/bin/ruby

print

"

Hello World

"

print

"

Good Morning

"

The above example produces the following output:


Hello WorldGood Morning

Opening and Closing Files

Up to now, you have read from and written to standard input and output. Now, we will look at how to manipulate actual data files.

File.new Method

You can use the File.new method to create an array of File objects are used for reading, writing, or both, with access determined by the mode parameter. Finally, you can use the File.close method to close the file.

Syntax

aFile

=

File

.

new

(

"

filename

"

,

"

mode

"

)

... Handling Files

aFile

.

close

File.open Method

You can use the File.open method creates a new file object and assigns it to the file. However,File.open and File.new there is a slight difference between the methods. The difference is that File.open method can be associated with a block, while File.new method cannot.

File

.

open

(

"

filename

"

,

"

mode

"

)

do

|

aFile

|

... process the file

end

The following table lists the different modes for opening a file:

Mode Description
r Read-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.
w Write-only mode. If the file exists, it is overwritten. If the file does not exist, a new file is created for writing.
w+ Read-write mode. If the file exists, the existing file is overwritten. If the file does not exist, a new file is created for reading and writing.
a Write-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

The methods used for simple I/O can also be used on all file objects. So, gets reads a line from standard input, andaFile.gets reads a line from the file object aFile.

However, I/O objects provide additional sets of access methods for our convenience.

sysread Method

You can use the method sysread to read the contents of a file. When using the method sysread, 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 will input the first 20 characters of the file. The file pointer will be placed at the 21st character in the file.

syswrite Method

You can use the method syswrite to write content to a file. When using the method syswrite, 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_byte Method

This method belongs to the class File. The method each_byte can iterate over each character in a string. See 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

Characters are passed one by one to the variable ch, then displayed on the screen, as follows:


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.readlines Method

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

IO.readlines is a method in the IO class. This method returns the contents of a file line by line. The following code shows the method IO.readlines :

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 file input.txt each line of will be an element in the array arr. Therefore, arr[0] will contain the first line, and arr[1] will contain the second line of the file.

IO.foreach Method

This method also returns output line by line. The method foreach and the method readlines differ in that the method foreach is associated with a block. However, unlike the method readlines, the method foreach does not return an array. For example:

Example

!/usr/bin/ruby

IO

.

foreach

(

"

input.txt

"

)

{|

block

|

puts

block

}

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

Renaming and Deleting Files

You can add captions to slides through the rename and delete methods to rename and delete files.

The following example renames an existing file test1.txt:

Example

!/usr/bin/ruby

Rename the file test1.txt to test2.txt

File

.

rename

(

"

test1.txt

"

,

"

test2.txt

"

)

The following example deletes an existing file test2.txt:

Example

!/usr/bin/ruby

Delete the file test2.txt

File

.

delete

(

"

text2.txt

"

)

File Modes and Ownership

Use the chmod method with a mask to change the file's mode or permission/access list:

The following example changes an existing file test.txt to a mask value:

Example

!/usr/bin/ruby

file

=

File

.

new

(

"

test.txt

"

,

"

w

"

)

file

.

chmod

(

0755

)

The following table lists the chmod The different masks available in the method:

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

File Queries

The following command checks whether a file exists before opening it:

Example

!/usr/bin/ruby

File

.

open

(

"

file.rb

"

)

if

File

::

exists

?

(

"

file.rb

"

)

The following command queries whether a file is actually a file:

Example

!/usr/bin/ruby

Returns true or false

File

.

file

?

(

"

text.txt

"

)

The following command checks whether the given filename 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 a 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 a file is zero in size:

Example

!/usr/bin/ruby

File

.

zero

?

(

"

test.txt

"

)

=> true

The following command returns the size of a file:

Example

!/usr/bin/ruby

File

.

size

?

(

"

text.txt

"

)

=> 1002

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

Example

!/usr/bin/ruby

File

::

ftype

(

"

test.txt

"

)

=> file

The ftype method identifies the type of a 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 a 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.File class is used to handle files,Dir class is used to handle directories.

Browsing Directories

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

Dir

.

chdir

(

"

/usr/bin

"

)

You can view the current directory with * Dir.pwd*:

puts

Dir

.

pwd

Returns the current directory, similar to /usr/bin

You can use the Dir.entries Get a list of files and directories within a specified directory:

puts

Dir

.

entries

(

"

/usr/bin

"

)

.

join

(

'

'

)

Dir.entries Returns an array containing all entries within the specified directory.Dir.foreach Provides the same functionality:

Dir

.

foreach

(

"

/usr/bin

"

)

do

|

entry

|

puts

entry

end

A more concise way to get a directory listing is by using Dir's class array methods:

Dir

[

"

/usr/bin/*

"

]

Create a directory

Dir.mkdir can be used to create a directory:

Dir

.

mkdir

(

"

mynewdir

"

)

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

**Note:** The mask 755 sets the permissions for the owner, group, and world [anyone] to rwxr-xr-x, where r = read, w = write, and x = execute.

Dir

.

mkdir

(

"

mynewdir

"

,

755

)

Delete directory

Dir.delete can be used to delete a directory.Dir.unlink and Dir.rmdir performs the same function, for our convenience.

Dir

.

delete

(

"

testdir

"

)

Creating Files & Temporary Directories

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

Dir.tmpdir provides the path to the temporary directory on the current system, but this method is not available by default. To make Dir.tmpdir available, it is necessary to use the required 'tmpdir'.

You can use Dir.tmpdir and File.join together 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 named Tempfile 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: