From: Rob Biedenharn Date: 2008-09-24T22:48:45+09:00 Subject: Re: update a field in CSV file using fastercsv On Sep 24, 2008, at 8:53 AM, James Gray wrote: > On Sep 24, 2008, at 7:16 AM, Pit Capitain wrote: > >> 2008/9/21 Gregory Brown : >>> The reason we need to do things this way is that (at least in Ruby, >>> but in most languages I'd imagine), there isn't really a way to >>> make a >>> change to a file while you're reading it. >> >> Sorry, Greg, but that's not correct. See the following example. >> >> Create a file with three lines: >> >> ... >> Now read a line, write something, and read a line again: >> >> File.open(name, "r+") do |file| >> puts file.gets >> file.puts "new data" >> puts file.gets >> end > > This has pretty limited use. It's rare that you can get away with > chopping up a file like this, in my opinion. > > James Edward Gray II If you're dealing with a file containing fixed-size records (even if they are text), it can be quite useful. For your average text file which is treated as a collection of "lines" with varying length, this is never going to be easy. Overwriting is easy; deleting can be handled by maintaining two positions in the file and cycling reading, repositioning, writing, and repositioning until truncating the "extra" bytes that are left at the end; inserting is tough because you have to keep track of the bytes that don't fit in the original file until you reach the end and can append. That's why is is usually so much easier to read to memory, make your changes, and write to a new file. -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com