當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby IO.read用法及代碼示例

本文簡要介紹ruby語言中 IO.read 的用法。

用法

read(maxlen = nil) → string or nil
read(maxlen = nil, out_string) → out_string or nil

從流中讀取字節(二進製模式):

  • 如果 maxlennil ,則讀取所有字節。

  • 否則讀取 maxlen 字節(如果可用)。

  • 否則讀取所有字節。

返回包含讀取的字節的字符串(新字符串或給定的 out_string )。字符串的編碼取決於 maxLenout_string

  • maxlen is nil :使用 self 的內部編碼(不管是否給出了 out_string)。

  • maxlen 不是 nil

    • out_string 給定:out_string 的編碼未修改。

    • out_string 未給出:使用 ASCII-8BIT。

沒有參數 out_string

當參數out_string被省略時,返回值是一個新字符串:

f = File.new('t.txt')
f.read
# => "This is line one.\nThis is the second line.\nThis is the third line.\n"
f.rewind
f.read(40)      # => "This is line one.\r\nThis is the second li"
f.read(40)      # => "ne.\r\nThis is the third line.\r\n"
f.read(40)      # => nil

如果maxlen 為零,則返回一個空字符串。

帶參數out_string

當給定參數 out_string 時,返回值為 out_string ,其內容被替換:

f = File.new('t.txt')
s = 'foo'      # => "foo"
f.read(nil, s) # => "This is line one.\nThis is the second line.\nThis is the third line.\n"
s              # => "This is line one.\nThis is the second line.\nThis is the third line.\n"
f.rewind
s = 'bar'
f.read(40, s)  # => "This is line one.\r\nThis is the second li"
s              # => "This is line one.\r\nThis is the second li"
s = 'baz'
f.read(40, s)  # => "ne.\r\nThis is the third line.\r\n"
s              # => "ne.\r\nThis is the third line.\r\n"
s = 'bat'
f.read(40, s)  # => nil
s              # => ""

請注意,此方法的行為類似於 C 中的 fread() 函數。這意味著它會重試調用 read(2) 係統調用以使用指定的 maxlen(或直到 EOF)讀取數據。

即使流處於非阻塞模式,也會保留此行為。 (此方法與其他方法一樣對非阻塞標誌不敏感。)

如果您需要像單個 read(2) 係統調用這樣的行為,請考慮 readpartial read_nonblock sysread

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 IO.read。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。