开发者

Writing to file using the .insert string method

开发者 https://www.devze.com 2023-03-06 11:10 出处:网络
Best way 开发者_如何学Cto code writing to a specific point in a file using r+ mode and the .insert method?

Best way 开发者_如何学Cto code writing to a specific point in a file using r+ mode and the .insert method?

gets.chomp is used and attached to a variable called x it is this variable and the assigned string that needs to be inserted at a specific position when writing to a file.

Thanks


You can replace or insert stuff in a file. Scroll to 'Modifying a File in Place Without a Temporary File' on Pleac . It's fragile and not considered good practise. The usual way is:

  • read the original file
  • Modify the content in memory
  • Write it to a temporary file
  • (Optionally) rename the original file to something like orig_file.old
  • Rename the temporary file to the originale filename.

This way minimalizes the chance of data loss in case of powerouts and the like.

Update: according to your comment you need something like

File.open('test.txt', 'r+') do |f|
  str = f.read
  f.rewind
  f.write( str.insert(6, ' HI THERE '))
end
0

精彩评论

暂无评论...
验证码 换一张
取 消