Page 1 of 1

Appending to the body of a file

Posted: Mon Jun 02, 2003 8:26 pm
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]

Posted: Mon Jun 02, 2003 8:29 pm
by bradvan
The function just finds the position to write from, I fwrite() the line elswhere.

Posted: Tue Jun 03, 2003 2:43 am
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.