1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

#yokohamarb 「Rubyレシピブック」recipe 194「ファイルに1行挿入する」の修正

Posted at

ポイントはコメントに書いたとおりです。
元のTempfile.newの代わりにTempfile.createを、File.renameの代わりにFileUtils.cpを使いました。
Tempfile.createって知らなかった。
openと違って、付属のブロックを抜けた時、作成した一時ファイルを削除します。
今度からこっち使おう。

require 'tempfile'
require 'fileutils'

def insert path, start_line, data
  pid = Process.pid.to_s 
  Tempfile.create pid, File.dirname(path) do|temp|
    File.open(path) do|input|
      start_line.times do
        if line = input.gets
          temp.write line
        end
      end
      temp.puts data
      while line = input.gets
        temp.write line
      end
    end
    temp.flush
    mode = File.stat(path).mode
    # File.renameだとpathとtemp.pathのあるファイルシステムが違う場合、うまく行かない。
    # どうせTempfile.createメソッドのブロックを出るときにtempは削除されるはずなので、cpする。
    FileUtils.cp(temp.path, path)
    File.chmod(mode, path)
  end
end

insert ARGV[0], ARGV[1].to_i, ARGV[2]
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?