本文簡要介紹ruby語言中 IO.read
的用法。
用法
read(maxlen = nil) → string or nil
read(maxlen = nil, out_string) → out_string or nil
從流中讀取字節(二進製模式):
-
如果
maxlen
是nil
,則讀取所有字節。 -
否則讀取
maxlen
字節(如果可用)。 -
否則讀取所有字節。
返回包含讀取的字節的字符串(新字符串或給定的 out_string
)。字符串的編碼取決於 maxLen
和 out_string
:
-
maxlen
isnil
:使用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 IO.read用法及代碼示例
- Ruby IO.readlines用法及代碼示例
- Ruby IO.readchar用法及代碼示例
- Ruby IO.readpartial用法及代碼示例
- Ruby IO.read_nonblock用法及代碼示例
- Ruby IO.rewind用法及代碼示例
- Ruby IO.reopen用法及代碼示例
- Ruby IO.raw用法及代碼示例
- Ruby IO.eof用法及代碼示例
- Ruby IO.fileno用法及代碼示例
- Ruby IO.pread用法及代碼示例
- Ruby IO.to_i用法及代碼示例
- Ruby IO.self << object用法及代碼示例
- Ruby IO.tty?用法及代碼示例
- Ruby IO.close_write用法及代碼示例
- Ruby IO.write_nonblock用法及代碼示例
- Ruby IO.set_encoding_by_bom用法及代碼示例
- Ruby IO.syswrite用法及代碼示例
- Ruby IO.close_read用法及代碼示例
- Ruby IO.stat用法及代碼示例
- Ruby IO.pwrite用法及代碼示例
- Ruby IO.ungetc用法及代碼示例
- Ruby IO.noecho用法及代碼示例
- Ruby IO.new用法及代碼示例
- Ruby IO.sysopen用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 IO.read。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。