Introduction to file operations in Ruby and file operations in ruby

Source: Internet
Author: User

Introduction to file operations in Ruby and file operations in ruby

Ruby provides a complete set of I/O-related kernel modules. All I/O methods come from IO classes.

Class IO provides all the basic methods, such as read, write, gets, puts, readline, getc, and printf.

This chapter covers all basic I/O functions available in Ruby. For more functions, see Ruby IO class.
Puts statement:

In the previous section, you specify the value variable and then use the Declaration puts output.

Puts indicates that the program is stored in the variable value. This will add a new row and write (output) at the end of each line ).
Example:

#!/usr/bin/rubyval1 = "This is variable one"val2 = "This is variable two"puts val1puts val2

This produces the following results:

This is variable oneThis is variable two

Gets statement:

The gets statement can be used to take input from the user's standard screen to call STDIN.
For example:

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

#!/usr/bin/rubyputs "Enter a value :"val = getsputs val

This produces the following results:

Enter a value :This is entered valueThis is entered value

Putc statement:

Unlike the puts statement, the putc statement outputs the entire string on the screen, which can be used to output one character at a time.
Instance:

The output of the following code is only a character H:

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

This produces the following results:

H

Print statement:

The print statement is similar to the puts statement. The only difference is that after the puts statement enters the content printed in the next line, the print statement positions the cursor on the same line.
Instance:

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

This produces the following results:

Hello WorldGood Morning

Open and Close files:

Up to now, we have been able to read and write standard input and output. We will look at how to apply it to actual data files.
File. new Method:

You can create a File object using the read, write, or both of the File. new method, depending on the mode string. Finally, you can use File. close to close the File.
Syntax:

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

File. open method:

You can use the File. open method to create a new File object and allocate it to a File. However, there is a difference between the File. open Method and the File. new method. The File. open method is different. A block can be associated, but cannot be used in the File. new method.

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

Here is a list of open files in different modes:

Read and Write files:

In the same way, we have been using "simple" I/O all file objects. Therefore, gets reads a row from the standard input, and the File. gets File reads a row from the File object.

However, I/O objects provide additional access methods to make our life easier.
Sysread method:

Sysread can be used to read the content of a file. The sysread method used in any mode when the file can be opened. For example:

The following is an input text file:

This is a simple text file for testing purpose.

Now, let's try to read this file:

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

This statement will output the first 20 characters of the file. Now, put the file pointer in 21st characters.
Syswrite method:

You can use this method to write the content in syswrite to a file. You need to open this file when using syswrite in write mode.
For example:

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

This statement writes "ABCDEF" to the file.
Each_byte method:

This method belongs to the File class. It is always associated with a block method each_byte. Consider the following code example ::

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

The variable ch is passed one by one, and then displayed on the screen as follows:

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 IO class. Class IO also has some methods for file operations.

One of the methods of the IO class is IO. readlines. The content file line returned by this method. The following code shows how to use IO. readlines:

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

In this Code, the variable arr is an array. Place each line of the file input.txt and the elements in the array arr. Therefore, arr [0] will be included in the first line, and arriving at [1] will include the second line of the file.
IO. foreach method:

This method also returns the output of a row. The difference between the foreach and readlines methods is that the foreach method can be associated with blocks, and foreach does not return an array. For example:

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

This code will pass the content of the file, test the line of the variable block, and then the output will be displayed on the screen.
Rename and delete files:

Rename and delete methods can be used programmatically in Ruby to rename and delete files.

In the following example, rename the existing file test1.txt:

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

The following example deletes the existing file test2.txt:

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

File mode and ownership:

Use the chmod mask to change the mode or permission/Access File List:

The following example shows the test.txt pattern mask value of the file:

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

The following table helps to select different masks as the chmod method:

File query:

Run the following command to test whether a file exists and then open it:

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

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

#!/usr/bin/ruby# This returns either true or falseFile.file?( "text.txt" ) 

If the given file name is a directory, run the following command to find it:

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

The following Command finds whether the file is readable, writable, or executable:

#!/usr/bin/rubyFile.readable?( "test.txt" )  # => trueFile.writable?( "test.txt" )  # => trueFile.executable?( "test.txt" ) # => false

Run the following command to check whether the file size is zero or not:

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

The file size returned by the following command:

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

You can use the following command to find a type of file:

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

The ftype method returns one of the following types: file, directory, characterSpecial, blockSpecial, fifo, link, socket, or unknown.

The following command can be used to find out when a file is created, modified, or accessed last time:

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

Ruby directory:

All files are included in different directories, and Ruby does not handle these problems. In view of File class processing, the directory is used to process the Dir class.
Navigate through the directory:

To change the directory of a Ruby program, use Dir. chdir as follows. This example changes the current directory/usr/bin.

Dir.chdir("/usr/bin")

You can use Dir. pwd to find out what the current directory is:

puts Dir.pwd # This will return something like /usr/bin

To obtain a list of files and directories in a specific directory, use Dir. entries:

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

Dir. entries returns all items in the specified directory of an array. Dir. foreach provides the same functions:

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

A simpler method to obtain the directory list using the Dir array:

Dir["/usr/bin/*"]

Create a directory:

You can use Dir. mkdir to create a directory:

Dir.mkdir("mynewdir")

You can also set a new directory permission (not an existing one) using mkdir:

Note: mask 755 sets the permission owner. The Group indicates that [Everyone] is similar to rwxr-xr-x, r = read, w = write, and x = execute.

Dir.mkdir( "mynewdir", 755 )

Delete directory:

You can use Dir. delete to delete a directory. Dir. unlink and Dir. rmdir perform the same functions and provide convenience.

Dir. delete ("testdir ")

Create files and temporary directories:

Temporary files are temporary files that may be generated during program execution, but are not permanently stored.

Dir. tmpdir provides the path to the temporary directory of the current system, although this method is unavailable by default. 'Tmpdir' is required for Dir. tmpdir '.

You can use Dir. tmpdir and File. join to create a temporary File independent of the Platform:

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, and deletes it. The Ruby standard library also contains a program library Tempfile, which can create temporary files:

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

Built-in functions:

Here is a complete list of Ruby support functions that process files and directories:

  • File Class and Methods.
  • Dir Class and Methods.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.