RUBY文件读写

11.读写

    标准输入流:gets 读文件 

              File.open("hello.rb","r") do |file|

               while line  = file.gets

                   puts line #打印出文件内容

               end

             end

    标准输出流:puts
    print
    两者的区别是puts会在参数后面添加回车换行,print不会添加
    printf("Number:%5.2f,\nString:%s\n",1.23,"hello") 这个语法跟c相同就不多说了
    %5.2f  匹配  1.23

    %s  匹配字符串

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


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值