Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^2: Write in files

by Random_Walk (Prior)
on Nov 18, 2013 at 11:26 UTC ( [id://1063065]=note: print w/replies, xml ) Need Help??


in reply to Re: Write in files
in thread Write in files

One problem you will have, if you try to update files 2, is that you can not write a new, longer line, into the middle of file 2, without overwriting the following data:

# Original file 2: Bloggs,Fred\n Conner,Sarah\n Bloggs,Joe\n # file 2 after adding Fred's phone Number Bloggs,Fred,0234687821\n h\n Bloggs,Joe\n
As you can see, poor old Sarah Conner, has been terminated. Follow the advice to build a new file, and if required remove (or rename) the old file 2, and rename the new one, to the original name, when done.

Cheers,
R.

Pereant, qui ante nos nostra dixerunt!

Replies are listed 'Best First'.
Re^3: Write in files
by lolz (Initiate) on Nov 18, 2013 at 12:09 UTC
    how would the code be for editing the original file?

    just because i want to know how that would work :)

      It would be ugly. You would have to copy the file from the end of your current line, update the current line, then put the copied data back, after your new file position. I actually started to write some example code, but it is such a terrible idea I quickly gave up.

      You would probably load the entire file into an array, line per record, then go through the array, keeping a note of how many bytes into the file you are. When you update a record, seek to the end of the old record, before its \n, write the additional info plus new \n, then overwrite the rest of the file with the rest of the records in your array. If you really want to keep the same file, it would be better to build the entire new record set in memory, then blat it all out in one go, overwriting the old file. Power loss, or a crash, will probably cause data loss.

      If you really want to go mad, you could process one record at a time, then when you came to write out, read a few records from your file, write your data, then do a sort of read/write shuffle through the file to move everything up a few bytes. For this approach to work, you would have to be smoking something pretty special ;-)

      Cheers,
      R.

      Pereant, qui ante nos nostra dixerunt!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1063065]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2024-04-23 23:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found