Insert rows on specific line in a file

后端 未结 2 1433
感动是毒
感动是毒 2021-01-07 09:32

I have opened my existing file in r+ mode.

open(\"#{RAILS_ROOT}/locale/app.pot\", \'r+\') do |f|

end

I want to insert some other rows at specific lin

相关标签:
2条回答
  • 2021-01-07 09:35

    This has worked for me in the past:

    def write_at(fname, at_line, sdat)
      open(fname, 'r+') do |f|
        while (at_line-=1) > 0          # read up to the line you want to write after
          f.readline
        end
        pos = f.pos                     # save your position in the file
        rest = f.read                   # save the rest of the file
        f.seek pos                      # go back to the old position
        f.write sdat                    # write new data
        f.write rest                    # write rest of file
      end
    end
    
    0 讨论(0)
  • 2021-01-07 09:52

    This may not be the best Ruby way, but in general when I have had to do this in the past, I would open an output file with a globally unique name and go line by line reading and writing from one to the other, keeping line count along the way. (it isn't the greatest thing in the world to maintain, but it's very simple to implement)

    0 讨论(0)
提交回复
热议问题