Jump to content

Archived

This topic is now archived and is closed to further replies.

royrules22

File writing problems/optimization

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..

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites
Hmm.. That would be a valid solution, but I still can't get over the fact that there's a lot of unnecessary extra resources being used (in this case the temp file). Isn't there a way to just seek to the link # and insert there?

Share this post


Link to post
Share on other sites

×

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.