11.读写
标准输入流:gets 读文件
File.open("hello.rb","r") do |file|
while line = file.gets
1.先写段代码看看
#p1
myFile = File.new("f:\\ruby\\mycode\\hello.rb","w");
myFile.puts "puts 'aa'"
myFile.puts "puts 'bb'"
myFile.close #只有close掉了内容才被写入文件里面。
windows中路径 "\\"
文件hello.rb写入上面两行代码
创建文件:File.new("hello.rb","w")
删除文件:File.delete("")
读取文件:File.open("hello.rb","r") do |file|
while line = file.gets #标准输入流
puts line
end
end
#读文件
print "Please input a file name:"
filename = gets
if filename &&!filename.empty?#文件存在
filename = filename[0,filename.length-1]
#去掉文件名后面的"\n"
else
print "the file name can't be null!"
exit(1)
end
if File.exist?(filename)
puts "=========#{filename}========="
File.open(filename,"r") do |file|
while line = file.gets
puts line
end
end
puts "=================="
else
puts "the program can't find the file #{filename}"
end
print "Press any key to contiue..."
gets
#写文件
puts "======================================"
puts "This program is about Ruby write file."
puts "======================================"
print "Please input file name: "
filename=gets
if filename&&!filename.empty?
filename=filename[0, filename.length-1]
else
puts "The file name can't been null!!"
exit 1;
end
file=nil
unless File.exist?(filename)#条件不成立的时候执行
puts "The system cannot find the file specified!"
print "[C] to create a new file and [E] to exit the program: "
option=gets
if option&&!option.empty?
option=option.chomp#去掉"\n"
else
puts "bye!"
exit 1;
end
case option.downcase
when "c" : file=File.new(filename, "w")
when "e" : exit 0
else
puts "Invalid arguments!! The program has stop. "
exit 0
end
else
file=File.new(filename, "w")
end
print "Now please input content: "
content=gets
file.print content
file.close
print "Press any key to continue...."
gets
puts line #打印出文件内容
end
end
两者的区别是puts会在参数后面添加回车换行,print不会添加
printf("Number:%5.2f,\nString:%s\n",1.23,"hello") 这个语法跟c相同就不多说了
%5.2f 匹配 1.23
%s 匹配字符串