Appending to the body of a file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
bradvan
Forum Newbie
Posts: 10
Joined: Mon Jun 02, 2003 8:26 pm
Location: Rylstone, Australia
Contact:

Appending to the body of a file

Post by bradvan »

Is there a relatively simple way to add lines to a file at a specific point without destroying any other data in the file?

I am basically wanting to insert a new line of text into a file so that the lines stay in decending alphabetical order in reference to a specific word in each line.

I tried this code with no luck:

Code: Select all

function find_alpha_pos($target, $file, $delim)
{
 while (!feof($file))
 {
 	// record read position
	$read_pos = ftell($file);
	
 	// read line from file
 	$line = fgets($file);
	

	$parts = explode($delim, $line);
	if ($parts[1] == "") 
	{
	 $name = $parts[0];
	}
	else 
	{
	 $name = $parts[1];
	}
	
	if ($name < $target) continue;
	else
	{
	 fseek($file, $read_pos);
	 break;
	}
 }
}
mod_edit: added

Code: Select all

tags[/size]
User avatar
bradvan
Forum Newbie
Posts: 10
Joined: Mon Jun 02, 2003 8:26 pm
Location: Rylstone, Australia
Contact:

Post by bradvan »

The function just finds the position to write from, I fwrite() the line elswhere.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

read the remaining data of the file, write the new entry and append what you've read.
If the file is too big use a temp.file so you can do it in parts and move the temp.file when done.
Post Reply