Delete top 2 lines (was file management)

From: Date: Sat, 08 Sep 2001 01:19:00 +0000
Subject: Delete top 2 lines (was file management)
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-66506@lists.php.net to get a copy of this message
Here is what Im attempting.... $size = filesize("chat/chat.txt"); // get size of file if (filesize("chat/chat.txt") > 500) { // if over x bytes chop it down
        $fp = fopen("./chat/chat.txt", "r+"); // open a fp
        $count = 0;			      // setup a count
        while (!@feof($fp) && ($count < 2)) { //if not eof & < 2
                rewind($fp);		// go to beginning
                $bytes = fgets($fp, 4096); // get the # of bytes in line
                ftruncate($fp, $bytes);  // kill line with # of bytes
                $count = $count + 1; // increment count
        }				// end while loop
fclose($fp); 			// close fp
} 				// close if
here is what is happening currently, when the file goes over 500 bytes, the whole file gets dumped, not what I want. The form Im using can only put out 109 bytes plus /n total. In this example (if you want to call it one), I would like it to kill the first 2 lines in the file. Thanks to Hughes for putting me on to this, its a little clearer... Gerard Samuel wrote:
You know what, I think Im explaining myself wrong. The word truncate in itself means I believe to cut at the bottom. This isn't what I need. Basically, its a chat script and all the newer messages are at the bottom, and when the file reaches x bytes I want to 'cut off the head' of the file by x lines. leaving the most current messages at the bottom alone. Ive been messing around with truncate all this time getting the wrong results. Why cant files be as easy as databases.... :) If any one has a clue please point it to me. Meantime, back to the manual..... Thanks Sterling Hughes wrote: On Fri, 7 Sep 2001, Gerard Samuel wrote:
Can a file be truncated from the beginning, and by x amount of lines?? Thanks
    Truncated from the beginning?  Do you mean truncate the file by X
    lines, starting from the first position in the file, well, yeah:
    <?php
    $fp = fopen("filename", "r+");
    // Start counting from 0, set to one, if you want to start counting
    // from 1
    $count = 0;
    while (!@feof($fp)) {
        // Not used, but unless your line lengths are longer than
        // 4K, this will effectively skip over a line
        $line = fgets($fp, 4096);
        if (++$count == $line_number_you_want) {
            ftruncate($fp, ftell($fp));
        }
    }
    fclose($fp);
    ?>
    Please note the above is devoid of error checking :)
    -Sterling


« previous php.general (#66506) next »