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.

Class IO provides all 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. For more functions, check out Ruby's IO class.

puts Statement

In the previous chapters, you assigned values ​​to variables and then used the puts statement to print the output. The

puts statement instructs the program to display the value stored in the variable. This will add 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 output result of the above example is:

This is variable one
This is variable two

gets Statement

gets Statement Can be used to obtain user input from a standard screen called STDIN.

Example

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

#!/usr/bin/ruby

puts "Enter a value :"
val = gets
puts val

The output result of the above example is:

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

putc The statement

is different from the puts statement, puts The statement outputs an entire string to the screen, while the putc statement can be used to output characters one at a time.

Example

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

#!/usr/bin/ruby

str="Hello Ruby!"
putc str

The output result of the above example is:

H

print statement The

print statement is similar to the puts statement. The only difference is that the puts statement will jump to the next line after outputting the content, while when using the print statement, 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

As of now, you have read and written to the standard input and output. Now, we'll look at how to manipulate the actual data files.

File.new Method

You can use the File.new method to create a File object for reading, Write or read and write, read and write permissions depend on the mode parameter. Finally, you can close the file using the File.close method.

Syntax

aFile = File.new("filename", "mode")
   # ... 处理文件
aFile.close

File.open Method

You can use the File.open method to create a new file object, And assign the file object to the file. However, there is a little difference between the File.open and File.new methods. The difference is that the File.open method can be associated with a block, while the File.new method cannot.

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

The following table lists the different modes for opening files:

Mode Description
rRead-only mode. The file pointer is placed at the beginning of the file. This is the default mode.
r+Read and write mode. The file pointer is placed at the beginning of the file.
wWrite-only mode. If the file exists, the file is overwritten. If the file does not exist, a new file is created for writing.
w+Read and write mode. If the file exists, overwrite 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. In other words, the file is in append mode. If the file does not exist, a new file is created for writing.
a+Read and write mode. If the file exists, the file pointer is placed at the end of the file. In other words, 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 are also available for all file objects. So, gets reads a line from standard input and aFile.gets reads a line from the file object aFile.

However, the I/O object provides additional settings for access methods to provide us with convenience.

sysread Method

You can use method sysread to read the contents of a file. When using the sysread method, you can open the file in either 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:

#!/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 character 21 in the file.

syswrite Method

You can use method syswrite to write to a file. When using method syswrite you need to open the file in write mode. For 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 class File. Method each_byte is a method that can iterate each character in the string. Please look at the following code 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 to the variable ch one after another, and 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

ClassFile is a subclass of class IO. Class IO also has methods for manipulating files.

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

#!/usr/bin/ruby

arr = IO.readlines("input.txt")
puts arr[0]
puts arr[1]

In this code, the variable arr is an array. Each line of the file input.txt 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 difference between method foreach and method readlines is that method foreach is associated with a block. However, unlike method readlines, method foreach does not return an array. For example:

#!/usr/bin/ruby

IO.foreach("input.txt"){|block| puts block}

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

Renaming and deleting files

You can rename and delete files through the rename and delete methods.

The following example renames an existing file test1.txt:

#!/usr/bin/ruby

# 重命名文件 test1.txt 为 test2.txt
File.rename( "test1.txt", "test2.txt" )

The following example deletes an existing file test2.txt:

#!/usr/bin/ruby

# 删除文件 test2.txt
File.delete("text2.txt")

File Mode and Ownership

Use the chmod method with mask to change the mode or permissions/access list of a file:

below Example: Change the mode of an existing file test.txt to a mask value:

#!/usr/bin/ruby

file = File.new( "test.txt", "w" )
file.chmod( 0755 )

The following table lists the different masks that can be used in the chmod method. code:

MaskDescription
0700rwx mask, for owner
0400r for owner
0200w for owner
0100x , for the owner
0070rwx mask, for the group it belongs to
0040r , for the group it belongs to
0020w , for the group it belongs to
0010#x, for the group it belongs to
0007rwx mask, for others
0004r , for others
0002w , for others
0001x, for others
4000Set user ID when executing
2000Set the group ID when executing
1000Save the exchange text, even after use

File query

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

#!/usr/bin/ruby

File.open("file.rb") if File::exists?( "file.rb" )

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

#!/usr/bin/ruby

# 返回 true 或false
File.file?( "text.txt" )

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

#!/usr/bin/ruby

# 一个目录
File::directory?( "/usr/local/bin" ) # => true

# 一个文件
File::directory?( "file.rb" ) # => false

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

#!/usr/bin/ruby

File.readable?( "test.txt" )   # => true
File.writable?( "test.txt" )   # => true
File.executable?( "test.txt" ) # => false

The following command checks the file Whether the size is zero:

#!/usr/bin/ruby

File.zero?( "test.txt" )      # => true

The following command returns the size of the file:

#!/usr/bin/ruby

File.size?( "text.txt" )     # => 1002

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

#!/usr/bin/ruby

File::ftype( "test.txt" )     # => file

ftype method returns one of the following A certain value identifies the file type: file, directory, characterSpecial, blockSpecial, fifo, link, socket or unknown.

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

#!/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

Directory in Ruby

All files are contained in the directory, Ruby provides ways to work with files and directories. The File class is used to handle files, and the Dir class is used to handle directories.

Browse Directory

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 through Dir.pwd:

puts Dir.pwd # 返回当前目录,类似 /usr/bin

You can use Dir.entries to get the files and directories in the specified directory List:

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

Dir.entries Returns an array containing all entries in the specified directory. Dir.foreach provides the same functionality:

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

A more concise way to obtain a directory list is by using the Dir array-like method:

Dir["/usr/bin/*"]

Create a directory

Dir.mkdir Can be used to create a directory:

Dir.mkdir("mynewdir")

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

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

Dir.mkdir( "mynewdir", 755 )

Delete Directory

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

Dir.delete("testdir")

Creating Files & Temporary Directories

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

Dir.tmpdir Provides the path to the temporary directory on the current system, but this method is not available by default. It is necessary to use the required 'tmpdir' in order to make Dir.tmpdir available.

You can use Dir.tmpdir with File.join 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 paragraph The code creates a temporary file, writes data to it, and then deletes the file. Ruby's standard library also contains 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 processing in Ruby Complete list of built-in functions for files and directories:

  • File class and methods.

  • Dir class and method.