Page 1 of 1

Writing to specific line number

Posted: Sun Apr 18, 2004 12:04 am
by mgrd
Can someone please give me an example of how to write to a specific line number in a file so that it overwrites the line number in the process.

Posted: Sun Apr 18, 2004 12:32 am
by feyd

Code: Select all

if(is_file($filename) && is_readable($filename) && is_writable($filename) && ($contents = file($filename))!==false))
{
  if($contents&#1111;$line-1] <= sizeof($contents))
  &#123;
    $contents&#1111;$line-1] = $newline;
  &#125;
  file_put_contents($filename,$contents);
&#125;
this doesn't lock the file during the transaction, so something could overwrite the file mistakenly... although highly unlikely, unless you have many hits going at a time.

whoops, that's php5 only. :oops:

It's still possible to do it with php4.. you just have to fopen(), fwrite(), fclose() on your own instead of file_put_contents()..

Posted: Sun Apr 18, 2004 2:23 am
by JAM
Also, you could use file() to read the file into an array, then replace the $array[number] of choise...

Code: Select all

<?php
    $array = file('test.txt');
    // note, array starts at 0...
    $array[3] = 'Wohoooo'; // ...so line 4 is actually replaced
    $handle = fopen('test.txt', 'w+'); // open file, truncate to 0 lenght
    foreach ($array as $key => $val) {
        fwrite($handle, $val."\n"); // adding newlines using \n
    }
    fclose($handle);
?>
[Edit: Bad spelling and commented code better. --JAM]

Posted: Sun Apr 18, 2004 10:27 am
by tim
really nifty JAM, makes my method of doing that a waste of code. lol

kudos