Latest web development tutorials

Ruby file input and output

Ruby to provide a set of I / O-related methods implemented in the kernel (Kernel) module. All I / O method is derived from the IO class.

IOprovides all the class-based approach, such asread, write, gets, puts,readline, getc andprintf.

This section will explain all available Ruby-based I / O functions. For more functions, please see Ruby'sIOclass.

putsstatement

In the previous section, you assigned to a variable, and then use theputsstatement printout.

putsstatement indicates that the program displays the values stored in variables. This will add a new row at the end of each line.

Examples

#!/usr/bin/ruby

val1 = "This is variable one"
val2 = "This is variable two"
puts val1
puts val2

Run the above example output is:

This is variable one
This is variable two

getsStatement

getsstatement can be used to obtain user input from the standard screen called STDIN.

Examples

The following code demonstrates how to use gets statement. The code will prompt the user to enter a value that will be stored in the variable val, the final will be printed on STDOUT.

#!/usr/bin/ruby

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

Run the above example output is:

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

putcstatement

Andputsa different statement, the statementputsthe output of the whole string to the screen, whileputcstatement can be used to output a character sequence.

Examples

The output of the following code only character H:

#!/usr/bin/ruby

str="Hello Ruby!"
putc str

Run the above example output is:

H

printstatements

printstatements andputsa similar statement. The only difference is that after the statementputsthe output will jump to the next line, while the use ofprintstatement, the cursor is positioned on the same line.

Examples

#!/usr/bin/ruby

print "Hello World"
print "Good Morning"

Run the above example output is:

Hello WorldGood Morning

Opening and Closing Files

As of now, you have to read and write to the standard input and output. Now, we will look at how the actual data files.

File.newmethod

You can create aFileobject is used to readFile.newmethod, write or read and write, read and write permissions depending on mode parameters. Finally, you can useFile.closemethod to close the file.

grammar

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

File.openmethod

You can create a new file object usingFile.openmethod, and the object is assigned to the file file. However, there is one difference betweenFile.openandFile.newmethods. The difference isFile.openmethod can be associated with the block, but notFile.newmethod.

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

The following table lists the open files in different modes:

模式描述
r只读模式。文件指针被放置在文件的开头。这是默认模式。
r+读写模式。文件指针被放置在文件的开头。
w只写模式。如果文件存在,则重写文件。如果文件不存在,则创建一个新文件用于写入。
w+读写模式。如果文件存在,则重写已存在的文件。如果文件不存在,则创建一个新文件用于读写。
a只写模式。如果文件存在,则文件指针被放置在文件的末尾。也就是说,文件是追加模式。如果文件不存在,则创建一个新文件用于写入。
a+读写模式。如果文件存在,则文件指针被放置在文件的末尾。也就是说,文件是追加模式。如果文件不存在,则创建一个新文件用于读写。

Reading and writing files

The method for simple I / O can also be used for all file objects. So, gets reads a line from standardinput,aFile.gets aFile reads a line from the file object.

However, I / O object provides an additional set of access methods, provides us with convenience.

sysreadmethod

You can use the methodsysreadto read the contents of the file. When using the method sysread, you can use any one mode to open the file. E.g:

The following is the input text file:

This is a simple text file for testing purpose.

Now let's try to read the 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 enter the first 20 characters of the file. The file pointer will be placed in a position in the file 21 characters.

syswritemethod

You can use the methodsyswriteto write to the file. When using the method syswrite, you need to open the file in write mode. E.g:

#!/usr/bin/ruby

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

The statements are written "ABCDEF" to a file.

each_bytemethod

This method belongs to the classFile.Each_byte iterative method is able to string each character. Consider the following code examples:

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

One by one character is passed 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

Fileclass is a subclass of class IO. IO class also has some methods for manipulating files.

IO.readlinesis IO class a method. The progressive method returns the contents of the file. The following code shows a methodIO.readlinesuse:

#!/usr/bin/ruby

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

In this code, the variable is an array arr. Each row is an array arr fileinput.txtan element. Therefore, arr [0] will contain the first line, and arr [1] will contain the second line of the file.

IO.foreachmethod

The method also returns progressive output.Foreachbetween different methods and methodsreadlinesis associated methodforeachblock. However, unlike the methodreadlines,foreach method instead of returning an array. E.g:

#!/usr/bin/ruby

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

This code willtestthe contents of the file passed variable progressive block, then the output will be displayed on the screen.

Rename and delete files

You can rename and delete filesrenameanddeletemethods.

The following example renames a file that already existstest1.txt:

#!/usr/bin/ruby

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

The following example to delete an existing filetest2.txt:

#!/usr/bin/ruby

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

File mode and ownership

Usechmodto change the method with a mask pattern or file permissions / access list:

Examples of the following changes to an existing filetest.txtmodel for a mask value:

#!/usr/bin/ruby

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

The following table lists the different maskschmodmethod can be used:

掩码描述
0700rwx 掩码,针对所有者
0400r ,针对所有者
0200w ,针对所有者
0100x ,针对所有者
0070rwx 掩码,针对所属组
0040r ,针对所属组
0020w ,针对所属组
0010x ,针对所属组
0007rwx 掩码,针对其他人
0004r ,针对其他人
0002w ,针对其他人
0001x ,针对其他人
4000执行时设置用户 ID
2000执行时设置所属组 ID
1000保存交换文本,甚至在使用后也会保存

Document Access

The following command to check the file before opening the file already exists:

#!/usr/bin/ruby

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

The following command to query whether the file is really a file:

#!/usr/bin/ruby

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

Following command to check whether the given filename is a directory:

#!/usr/bin/ruby

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

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

Are the following command to check the file readable, writable, 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 size to 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 file:

#!/usr/bin/ruby

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

ftype method returns a value of the following to identify the type offile: file, directory, characterSpecial, blockSpecial, fifo, link, socketor unknown.

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

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

Ruby directory

All files are contained in the directory, Ruby provides a process files and directories.Fileclasses for working withfiles,Dir classes for working directory.

Browse the catalog

To change the directory in the Ruby program, please useDir.chdir.Examples of the following changes to the current directory is/ usr / bin.

Dir.chdir("/usr/bin")

You can view the current directoryDir.pwd:

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

Dir.entriesYou can get a list of files and directories inside the specified directory:

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

Dir.entriesreturns an array containing all the specified directory.Dir.foreachprovides the same functionality:

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

Get a directory listing of a more concise way is a method by using the Dir class array:

Dir["/usr/bin/*"]

Create a directory

Dir.mkdircan be used to create the directory:

Dir.mkdir("mynewdir")

You can also set permissions on the new directory (not existing directory) adopted mkdir:

Note: Mask 755 Set owner (owner), belongs to the group (group), everyone (world [anyone]) permissions rwxr-xr-x, where r = read read, w = write write, x = execute execution.

Dir.mkdir( "mynewdir", 755 )

Remove directory

Dir.deletebe used to delete directories.Dir.unlinkandDir.rmdirperform the same function, provides us with convenience.

Dir.delete("testdir")

File & Create a temporary directory

Temporary files are created that are simply in the process of execution of the program, but does not permanently stored information.

Dir.tmpdirprovides a path on the current system temporary directory, which by default, but is unavailable. To makeDir.tmpdiravailable, with the required 'tmpdir' is necessary.

You canDir.tmpdirandFile.joinused together to create a platform-independent temporary files:

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 in which to write data, and then delete the file. Ruby standard library also contains a library namedTempfile,and the library 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 files and directories in Ruby's built-in functions: