Input and output of Ruby files
Ruby provides a complete set of Istroke O-related methods, implemented in kernel (Kernel) modules. All the Icano 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 section will cover all the basic Imax O functions available in Ruby. For more functions, check out Ruby’s IO class.
puts
statement
In the previous section, you assigned a value to a variable and then used the puts
statement printout.
puts
statement instructs the program to display the value stored in the variable. This adds a new line at the end of each line.
Example
#!/usr/bin/rubyval1="This is variable one"val2="This is variable
two"putsval1putsval2
The output of the above instance is as follows:
This is variable one
This is variable two
gets
statement
gets
statement can be used to get data from a file named STDIN
the user input of the standard screen of
Example
The following code demonstrates how to use the gets
statement. The code will prompt the user for a value that will be stored in the variable val
will eventually be printed in the STDOUT
go.
Example
#!/usr/bin/rubyputs"Enter a value :"val=getsputsval
The output of the above instance is as follows:
Enter a value :
This is entered value
This is entered value
putc
statement
Different from the puts
statement, puts
statement outputs the entire string to the screen, while the putc
statement can be used to output one character in turn.
Example
The output of the following code is just characters H
:
Example
#!/usr/bin/rubystr="Hello Ruby!"putcstr
The output of the above instance is as follows:
H
print
statement
print
statement vs puts
statement is similar. The only difference is that puts
statement jumps to the next line after the output, using the print
statement, the cursor is positioned on the same line.
Example
#!/usr/bin/rubyprint"Hello World"print"Good Morning"
The output of the above instance is as follows:
Hello WorldGood Morning
Open and close files
As of now, you have read and written standard input and output. Now, we willlook at how to manipulate the actual data file.
File.new
method
You can use the File.new
method to create a File
object is used toread, write, or read and write, and the read and write permissions depend on the mode
parameters. Finally, you can use the File.close
methodto close the file.
Grammar
aFile=File.new("filename","mode")#... process the file aFile.close
File.open
method
You can use the File.open
method to create a new file
object and set the file
object is assigned to the file. But, File.open
and There is a slight difference between File.new
methods. The difference isthat File.open
method can be associated with a block, while the File.new
the method can’t.
File.open("filename","mode")do\|aFile\|#... process the fileend
The following table lists the different modes for opening files:
Pattern |
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 the mode. If the file exists, overwrite the file. 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, create a new file for reading and writing. |
A |
Write only the 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, create a new file for reading and writing. |
Read and write files
The method for simple Icano can also be used for all file
object. So, gets
reads a row from standard input aFile.gets
from file object aFile
read a row.
However, the Imap O object provides additional settings for accessing methods, which makes it convenient for us.
sysread method
You can use the method sysread
to read the contents of the file. When using 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’s try to read this file:
Example
#!/usr/bin/rubyaFile=File.new("input.txt","r")ifaFilecontent=aFile.sysread(20)putscontentelseputs"Unable
to open file!"end
This statement will enter the first 20 characters of the file. The file pointer will be placed in the position of the 21st character in the file.
syswrite
method
You can use the method syswrite
to write to the file. When using method syswrite
need to open the file in write mode. For example:
Example
#!/usr/bin/rubyaFile=File.new("input.txt","r+")ifaFileaFile.syswrite("ABCDEF")elseputs"Unable
to open file!"end
This statement will write “ABCDEF” to the file.
each_byte Method
This method belongs to the class File
. each_byte
method is an iterator that iterates over each character in a string. Take a look at the following code example:
Example
#!/usr/bin/rubyaFile=File.new("input.txt","r+")ifaFileaFile.syswrite("ABCDEF")aFile.rewindaFile.each_byte{\|ch\|putcch;putc?.
}elseputs"Unable to open file!"end
One character after another is passed 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.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 the file line by line. The following code shows the method IO.readlines
use:
Example
#!/usr/bin/rubyarr=IO.readlines("input.txt")putsarr[0]putsarr[1]
In this code, the variable arr
is an array. File input.txt
each row of will be an array arr
an element in the. Therefore, arr [0]
will contain the first line, while arr[1]
the second line of the filewill be included.
IO.foreach
method
This method also returns output line by line. Method foreach
and methods readlines
. The difference between them is that the method foreach
associated with a block. But, unlike the method, readlines
, method foreach
instead of returning an array. For example:
Example
#!/usr/bin/rubyIO.foreach("input.txt"){\|block\|putsblock}
This code will put the file test
is passed to the variable line by line block
and then the output is displayed on the screen.
Rename and delete files
You can use the rename
and delete
method 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.txtFile.rename("test1.txt","test2.txt")
The following example deletes an existing file test2.txt
:
Example
#!/usr/bin/ruby# delete file test2.txtFile.delete("text2.txt")
File mode and ownership
Use masked chmod
method to change the mode or permission / access list of the file:
The following example changes an existing file test.txt
is a mask value
Example
#!/usr/bin/rubyfile=File.new("test.txt","w")file.chmod(0755)
The following table lists chmod
the different masks that can be used in the
Mask |
Description |
---|---|
0700 |
Rwx mask for owner |
0400 |
R, for the owner |
0200 |
W, for the owner |
0100 |
X, for the owner |
0070 |
Rwx mask for the group it belongs to |
0040 |
R for the group to which it belongs |
0020 |
W for the group to which it belongs |
0010 |
X, for the group |
0007 |
Rwx mask for other people |
0004 |
R, aimed at other people |
0002 |
W, aimed at other people |
0001 |
X, for other people |
4000 |
Set user ID at execution time |
2000 |
Set the group ID when executing |
1000 |
Save the exchange text, even after use |
File query
The following command checks whether the file already exists before opening it:
Example
#!/usr/bin/rubyFile.open("file.rb")ifFile::exists?("file.rb")
The following command queries whether the file is indeed a file:
Example
#!/usr/bin/ruby# return true or falseFile.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 directory File::directory?("file.rb")#=> false
The following command checks whether the file is readable, writable, and executable:
Example
#!/usr/bin/rubyFile.readable?("test.txt")#=>
trueFile.writable?("test.txt")#=> trueFile.executable?("test.txt")#=>
false
The following command checks whether the file size is zero:
Example
#!/usr/bin/rubyFile.zero?("test.txt")#=> true
The following command returns the size of the file:
Example
#!/usr/bin/rubyFile.size?("text.txt")#=> 1002
The following command checks the type of file:
Example
#!/usr/bin/rubyFile::ftype("test.txt")#=> file
ftype
Method identifies the type of file by returning one of the following values: *file
、 directory
、 characterSpecial
、 blockSpecial
、 fifo
、 link
、 socket
or unknown*
.
The following command is used to check when the file was created, modified, or last accessed:
Example
#!/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
Directories in Ruby
All files are contained in directories, and Ruby provides a way to deal withfiles and directories. File
class is used to process files Dir
class is used to process directories.
Browse the catalog
To change the directory in the Ruby program, use the Dir.chdir
. The following example changes the current directory to /usr/bin
.
Dir.chdir("/usr/bin")
You can use the Dir.pwd
view the current directory:
putsDir.pwd# Return to the current directory, similar to /usr/bin
You can use the Dir.entries
get a list of files and directories in the specified directory:
putsDir.entries("/usr/bin").join('')
Dir.entries
returns an array of all items in the specified directory. Dir.foreach
provides the same functionality:
Dir.foreach("/usr/bin")do\|entry\|putsentryend
A more concise way to get a directory list is by using the Dir
the method of the class array of
Dir["/usr/bin/*"]
Create a directory
Dir.mkdir
can be used to create directories:
Dir.mkdir("mynewdir")
You can also use the mkdir
set permissions on the new directory (not anexisting directory):
Note: mask 755 sets owner (owner), group (group), everyone (world) [anyone] The permissions for) are rwxr-xr-x
, of which r = read
read, w =write
write x = execute
execute.
Dir.mkdir("mynewdir",755)
Delete directory
Dir.delete
can be used to delete directories. Dir.unlink
and Dir.rmdir
are convenient for us to perform the same function.
Dir.delete("testdir")
Create a file & temporary directory
Temporary files are information that is simply created during program execution but is not permanently stored.
The Dir.tmpdir
path to the temporary directory on the current system is provided, but this method is not available by default. In order to make Dir.tmpdir
available, use the necessary 'tmpdir'
is necessary.
You can put Dir.tmpdir
and File.join
to use together 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.closeFile.delete(tempfilename)
This code creates a temporary file, writes data to it, and then deletes the file. The standard library of Ruby also contains a library called Tempfile
that can be used to create temporary files
require'tempfile'f=Tempfile.new('tingtong')f.puts"Hello"putsf.pathf.close
Built-in function
The following provides a complete list of built-in functions in Ruby that deal with files and directories:
File classes and methods.
Dir classes and methods.