Replacing some bytes in middle of file

Discussion in 'PHP' started by chriseccles2, Sep 29, 2008.

  1. #1
    Does anyone have a method of replacing bytes inside a text file
    at the position determined by doing an fseek() ?
    -
    The 'a' mode in fopen() always defaults to appending to the end of
    file, and there doesn't appear to be any other listed way of, say,
    replacing a chunk of data in a fixed-record-length text file.
    -
    Can I use popen() to achieve this, maybe ?

    TIA

    -
    Chris
     
    chriseccles2, Sep 29, 2008 IP
  2. rohan_shenoy

    rohan_shenoy Active Member

    Messages:
    441
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    60
    #2
    Or you could extract the contents into a string, replace the necessary characters and replace the data in the file with the new string!
     
    rohan_shenoy, Sep 29, 2008 IP
  3. chriseccles2

    chriseccles2 Peon

    Messages:
    28
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks, rohan.
    -
    Yes, that's what I figured. Using file_get_contents() and explode().
    Then adjust the element in the array and use implode() and
    file_put_contents to restore it.
    -
    Trouble with that solution is that you need the file locked for a "long" time
    doing the overhead work, otherwise someone is reading the old data.
    If there was a way of simply writing to the middle, you wouldn't need the
    file at all until you were actually ready to write.
    -
    Shame there's no cleaner solution ! (Genuine random record writes
    to FRL files)
    -
    Chris
     
    chriseccles2, Sep 29, 2008 IP
  4. sastro

    sastro Well-Known Member

    Messages:
    214
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    105
    #4
    Learn regex like ereg_replace, preg_replace,str_replace etc.
     
    sastro, Sep 29, 2008 IP
  5. chriseccles2

    chriseccles2 Peon

    Messages:
    28
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    I'm OK with that, sastro ! The string manipulation stuff
    doesn't faze me at all. It was the file handling issue.
    -
    Like: You have a textfile of, say, "customers". It's fixed record
    length with delimit by length and padding. One customer changes
    their email address so you need to swap out that one FL record
    for another. With random access file writes, using an offset, that's
    a no-brainer. In PHP, it's a tad more code-heavy. That was all.
    :)

    -
    Chris
     
    chriseccles2, Sep 29, 2008 IP