Writing to specific line number

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
mgrd
Forum Newbie
Posts: 1
Joined: Sun Apr 18, 2004 12:04 am

Writing to specific line number

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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()..
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post 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]
Last edited by JAM on Sun Apr 18, 2004 12:49 pm, edited 1 time in total.
User avatar
tim
DevNet Resident
Posts: 1165
Joined: Thu Feb 12, 2004 7:19 pm
Location: ohio

Post by tim »

really nifty JAM, makes my method of doing that a waste of code. lol

kudos
Post Reply