Last active
October 25, 2017 11:20
-
-
Save Peranikov/167e64783dfb4fae1ded3b4d5704afde to your computer and use it in GitHub Desktop.
5–7 IO・File
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ファイルを読み込む | |
file = File.open('fname.txt') | |
puts file.read | |
file.close | |
# ブロックで記述するとすっきり書ける | |
File.open 'fname.txt' do |file| | |
puts file.read | |
end | |
# IO#getsはストリームから1行ずつ読み込む | |
File.open 'fname.txt' do |f| | |
while line = f.gets | |
puts line | |
end | |
end | |
# IO#each_lineでも可能 | |
File.open 'fname.txt' do |f| | |
f.each_line do |line| | |
puts line | |
end | |
end | |
# ファイルの中身をすべて文字列として取得する | |
File.read('.ruby-version') | |
# ファイルへの書き込み | |
# IO#writeでファイルへ書き込める(書き込みモードwを指定する必要あり) | |
File.open 'fname.txt', 'w' do |f| | |
f.write 'Hello' | |
end | |
# 複数モードを指定する | |
# ファイルを書き込みモードで開き、存在しなければ作成する | |
File.open 'foo', File::WRONLY | FILE::CREAT do |f| | |
f.puts 'puts' # "puts\n" と書き込む | |
f.puts # 改行のみ書き込む | |
f.print 'print' # "print" と書き込む | |
f.printf "%03d", 7 # "007" と書き込む | |
f.putc 97 # "a" と書き込む | |
end | |
# アクセス位置 | |
# IO#rewindでアクセス位置を先頭に戻すことができる | |
File.open 'fname.txt', 'a+' do |f| | |
f.puts '文字列を追記' | |
f.rewind # アクセス位置を先頭に戻す | |
puts f.read # 先頭から末尾まで取得 | |
end | |
# IO#seekで相対的にアクセス位置を変更できる | |
File.open 'fname.txt' do |f| | |
f.seek 10 # 先頭から10進んだ位置 | |
f.seek -10, IO::SEEK_CUR # 現在の位置から10戻った位置 | |
f.seek -10, IO::SEEK_END # 末尾から10戻った位置 | |
end | |
# IO#posで任意の位置に変更できる | |
File.open 'fname.txt' do |f| | |
f.pos = 30 # 任意の位置に移動 | |
f.pos # 現在の位置 | |
end | |
# エンコーディングの指定 | |
File.open 'fname.txt' do |f| | |
f.set_encoding('UTF-8') # 外部エンコーディングをUTF-8に設定 | |
f.set_encoding('EUC-JP', 'UTF-8') # 読み込みはEUC-JP => UTF-8、書き込みはUTF-8 => EUC-JPに変換する | |
f.set_encoding('EUC-JP:UTF-8') # :で区切って指定可能 | |
end | |
# エンコーディング情報の取得 | |
File.open 'fname.txt', 'r:euc-jp:utf-8' do |f| | |
puts f.external_encoding # "EUC-JP" | |
puts f.internal_encoding # "UTF-8" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment