zoukankan      html  css  js  c++  java
  • IO

    =begin
    #gets语句在sublime不可运行,在Dos窗口可运行
    puts "Enter a value :"
    val = gets
    puts val
    
    putc "hello"    # h
    
    #打开、关闭文件
    file = File.new("filename","r")
         #...处理文件
    file.close
    
    #File.open方法与new类似,但不同点在于File.open可与块相联
    File.open("filename","mode") do |aFile|
        #...处理文件
    end
    =end
    
    File.open("e:\test.txt","r") do |file|        # "r"可省略
        while line = file.gets
            puts line
        end
    end
    
    #读文件
    file = File.open("e:\test.txt","r")
    if file
        content = file.sysread(20)
        puts content
    else
        puts "can't open txt"
    end
    
    #写文件
    file = File.open("e:\test.txt","w")
    if file
        file.syswrite("modif")
    else
        puts "can't open txt"
    end
    
    #读到字符串里
    str = IO.read("e:\test.txt")
    puts str
    
    #读到数组里
    arr = IO.readlines("e:\test.txt")
    puts arr[0]
    
    #each_byte  可以迭代字符串中每个字符
    File.open("e:\test.txt","r") do |file|        
        file.each_byte {|ch| putc ch;print "."}
    end
    
    #foreach与块相关联,逐行返回输出,不像方法 readlines,方法 foreach 不是返回一个数组
    IO.foreach("e:\test.txt"){|block| puts block}
  • 相关阅读:
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    以太坊:通信协议对象 shh
    以太坊:Truffle 概述
    以太坊:快速入门 Truffle
  • 原文地址:https://www.cnblogs.com/stellar/p/5772826.html
Copyright © 2011-2022 走看看