RUBYファイル読み書き

2955 ワード

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]
        #        "
" 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# "
" 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の違いは、putsがパラメータの後ろに戻り改行を追加することであり、printはprintf(「Number:%5.2 f,String:%s」,1.23,「hello」)を追加しないという構文はcと同じであり、%5.2 fが1.23に一致するとは言わない
%s一致文字列