Jump to content

File writing problems/optimization


royrules22

Recommended Posts

Hi,

This is my first time here, and I wish I found this place earlier. In any case I'm a begginner at PHP. I used to code almost daily last year, however due to school and other issues I'vent touched PHP in over 6 months. And now I need to make a script (in a few days no less), and I'm stumped on this issue.

This script will recieve data from a form and format it. Than it will open up an HTML form, go to a specified line and insert the formatted input there. (Basically a news script designed around the website, rather than otherway which I would've preffered).

My solution was to read the entire file into an array using file(), opening up the file in "w" mode (in effect erasing the entire thing), write array from begginning to line "x" onto file, write the formatted ouput, and than finish writing the rest of the array. Close file.

This works, however I dislike having to load a huge file onto an array (about 40Kb and will grow), and than writing back from the array line by line.

My question is if there a better way to solve the problem? As in is the a way to just navigate to line x and than write there instead of having to load the stuff into an array? I thought of opening in a+ mode, fseeking to the position and writing. However I seem to remember reading somewhere that it will ALWAYS write to the end of the file if opened in append mode.

Thanks for the help.

Oh and the server is an IIS not Apache which I am more comfortable with..
Link to comment
Share on other sites

You could think about doing this (PSEUDOCODE):
[code]
fopen file. //No data loaded.
loop{
//Read in one line and append it to a temporary one
//Change the line(s) you want and append
}
unlink() old file.
rename temp file to old file.
[/code]

It seems roundabout but at least it doesn't have more than one line in memory at a time.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.