ruby输入与输出

ruby输入与输出_第1张图片
Paste_Image.png
ruby输入与输出_第2张图片
Paste_Image.png

下面ruby程序实现cat命令,把一个文本文件复制为一个新的文件
vim cat.rb
IO.copy_stream(STDIN,STDOUT)
然后执行:(前提是要有aaa.txt文件存在)
ruby cat.rb < aaa.txt > output.txt
我们查看是否复制了一个文件

ruby输入与输出_第3张图片
Paste_Image.png

字符串写入文件案例:


ruby输入与输出_第4张图片
Paste_Image.png

vim write.rb

File.dirname(FILE),表示当前文件的家目录,write.txt表示要写入内容的文件

abs_path = File.expand_path("write.txt",File.dirname(FILE))

绝对路径,下面2行是写入的文件内容

IO.write abs_path, < Line 1, first line
Line 2, second line
EOF

执行
ruby write.rb
[root@master1 ruby]# cat write.txt
Line 1, first line
Line 2, second line
[root@master1 ruby]#

字符串读入文件案例


ruby输入与输出_第5张图片
Paste_Image.png

vim read.rb

读取一个存在的文件

file_path = File.expand_path("write.txt",File.dirname(FILE))
puts(IO.read file_path)

读取一个不存在的文件

unexist_path = File.expand_path("unexist.txt",File.dirname(FILE))
begin
puts(IO.read unexist_path)
rescue SystemCallError => e
puts(e.class)
puts(e)
end

[root@master1 ruby]# ruby read.rb
Line 1, first line
Line 2, second line
Errno::ENOENT
No such file or directory - /m8/ruby/unexist.txt
[root@master1 ruby]#

你可能感兴趣的:(ruby输入与输出)