say have following ruby code which, given hash of insert positions, reads file , creates new file text inserted @ positions:
insertpos = {14=>25,16=>25} file.open('file.old', 'r') |oldfile| file.open('file.new', 'w') |newfile| oldfile.each_with_index |line,linenum| inserthere = insertpos[linenum] if(!inserthere.nil?)then line.insert(inserthere,"foo") end newfile.write(line) end end end
now, instead of creating new file, modify original (old) file. can give me hint on how modify code? thanks!
at fundamental level, extremely difficult thing do, in language, on operating system. envision file contiguous series of bytes on disk (this simplistic scenario, serves illustrate point). want insert bytes in middle of file. put bytes? there's no place put them! have "shift" existing bytes after insertion point "down" number of bytes want insert. if you're inserting multiple sections existing file, have multiple times! extremely slow, , run high risk of corrupting data if goes awry.
you can, however, overwrite existing bytes, and/or append end of file. unix utilities give appearance of modifying files creating new files , swapping them old. more sophisticated schemes, such used databases, allow inserts in middle of files 1. reserving space such operations (when data first written), 2. allowing non-contiguous blocks of data within file through indexing , other techniques, and/or 3. copy-on-write schemes new version of data written end of file , old version invalidated overwriting indicator of kind. not wanting go through trouble simple use case!
anyway, you've found best way you're trying do. thing you're missing fileutils.mv('file.new', 'file.old')
@ end replace old file new. please let me know in comments if can explain further.
(of course, can read entire file memory, make changes, , overwrite old file updated contents, don't believe that's you're asking here.)
Comments
Post a Comment