/    Sign up×
Community /Pin to ProfileBookmark

Overwriting certain parts of files only

Hey all, I’ve been using the file functions with PHP a lot lately, but there’s one problem I’m having. I know that when you open a file, you have options of what you want to do when you write to it (put new stuff at the beginning, end, or overwrite the original). However, I want to know if there is a way you can overwrite just part of the file.

Like, say you have a file that looks like:

bananas
eggs
milk

Is there a way you can open this file, and select the second line and overwrite it such that you could change the file to:

bananas
cheese
milk

Any help would be greatly appreciated, even if it’s a “no” :p

  • Chippp
  • to post a comment
    PHP

    1 Comments(s)

    Copy linkTweet thisAlerts:
    @SodbusterFeb 01.2009 — Yes, it can be done. But for small or moderate-size files your best bet is either to read the lines into an array with file() and replace the particular array element, or to read the file into a string and use, e.g., str_replace(). Then rewrite the file. The exact way you'd do it would depend on whether you want to replace a given line, or a line which contains a certain string, or something else. If the file is large you should look into breaking it up.

    Replacing mid-file can be done using ftell() and fseek(), but that can be tricky. If you write a string to particular place in the file, a part of the file equal to the length of the string will be overwritten. So, for example, if your file contains "bananasneggsnmilk" and you write "cheesen" starting from the "e" position in "eggsn", the resulting file will look something like "bananasncheesenlk". Writing "xn" would result in "bananasnxnsnmilk". Avoiding that can lead to some pretty convoluted code.

    The ultimate solution is to use a database, especially for frequently accessed and/or altered data.
    ×

    Success!

    Help @Chippp spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.25,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...