本文簡要介紹ruby語言中 IO.read 的用法。
用法
read(name, [length [, offset]] [, opt]) → string
read(name, [length [, offset]] [, opt]) → string
打開文件,可選擇查找給定的 offset ,然後返回 length 字節(默認為文件的其餘部分)。 read 確保文件在返回之前關閉。
如果 name 以管道字符 ("|" ) 開頭,並且接收者是 IO 類,則以與 Kernel#open 相同的方式創建子進程,並返回其輸出。考慮使用 File.read 來禁用子進程調用的行為。
選項
選項哈希接受以下鍵:
- :編碼
-
字符串或編碼
指定讀取字符串的編碼。如果指定了
length,將忽略:encoding。有關可能的編碼,請參閱Encoding.aliases。 - :模式
-
字符串或整數
指定open() 的
mode參數。它必須以“r” 開頭,否則會導致錯誤。有關可能模式的列表,請參閱IO.new。 - :open_args
-
數組
將 open() 的參數指定為數組。此 key 不能與
:encoding或:mode結合使用。
例子:
File.read("testfile") #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n"
File.read("testfile", 20) #=> "This is line one\nThi"
File.read("testfile", 20, 10) #=> "ne one\nThis is line "
File.read("binfile", mode: "rb") #=> "\xF7\x00\x00\x0E\x12"
IO.read("|ls -a") #=> ".\n..\n"...
相關用法
- 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 IO.try_convert用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 IO.read。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
