PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 18.16 Removing the Last Line of a File

18.16.1 Problem

You want to remove the last line of a file; for example, someone's added a comment to the end of your guestbook. You don't like it, so you want to get rid of it.

18.16.2 Solution

If the file is small, you can read it into an array with file( ) and then remove the last element of the array:

$lines = file('employees.txt');
array_pop($lines);
$file = join('',$lines);

18.16.3 Discussion

If the file is large, reading it into an array requires too much memory. Instead, use this code, which seeks to the end of the file and works backwards, stopping when it finds a newline:

$fh = fopen('employees.txt','r') or die("can't open: $php_errormsg");
$linebreak = $beginning_of_file = 0;

$gap = 80;
$filesize = filesize('employees.txt');
fseek($fh,0,SEEK_END);

while (! ($linebreak || $beginning_of_file)) {
    // save where we are in the file 
    $pos = ftell($fh);

    /* move back $gap chars, use rewind() to go to the beginning if
     * we're less than $gap characters into the file */ 
    if ($pos < $gap) {
        rewind($fh);
    } else {
        fseek($fh,-$gap,SEEK_CUR);
    }

    // read the $gap chars we just seeked back over 
    $s = fread($fh,$gap) or die($php_errormsg);

    /* if we read to the end of the file, remove the last character
     * since if it's a newline, we should ignore it */
    if ($pos + $gap >= $filesize) {
        $s = substr_replace($s,'',-1);
    }

    // move back to where we were before we read $gap chars into $s 
    if ($pos < $gap) {
        rewind($fh);
    } else {
        fseek($fh,-$gap,SEEK_CUR);
    }
    
    // is there a linebreak in $s ? 
    if (is_integer($lb = strrpos($s,"\n"))) {
        $linebreak = 1;
        // the last line of the file begins right after the linebreak 
        $line_end = ftell($fh) + $lb + 1;
    } 

    // break out of the loop if we're at the beginning of the file 
    if (ftell($fh) == 0) { $beginning_of_file = 1; }

}
if ($linebreak) {
    rewind($fh);
    $file_without_last_line = fread($fh,$line_end) or die($php_errormsg);
}
fclose($fh) or die("can't close: $php_errormsg");

This code starts at the end of the file and moves backwards in $gap character chunks looking for a newline. If it finds one, it knows the last line of the file starts right after that newline. This position is saved in $line_end. After the while loop, if $linebreak is set, the contents of the file from the beginning to $line_end are read into $file_without_last_line.

The last character of the file is ignored because if it's a newline, it doesn't indicate the start of the last line of the file. Consider the 10-character file whose contents are asparagus\n. It has only one line, consisting of the word asparagus and a newline character. This file without its last line is empty, which the previous code correctly produces. If it starts scanning with the last character, it sees the newline and exits its scanning loop, incorrectly printing out asparagus without the newline.

18.16.4 See Also

Section 18.15 discusses fseek( ) and rewind( ) in more detail; documentation on array_pop( ) at http://www.php.net/array-pop, fseek( ) at http://www.php.net/fseek, and rewind( ) at http://www.php.net/rewind.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    Chapter 5. Variables
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    18.1 Introduction
    Recipe 18.2 Creating or Opening a Local File
    Recipe 18.3 Creating a Temporary File
    Recipe 18.4 Opening a Remote File
    Recipe 18.5 Reading from Standard Input
    Recipe 18.6 Reading a File into a String
    Recipe 18.7 Counting Lines, Paragraphs, or Records in a File
    Recipe 18.8 Processing Every Word in a File
    Recipe 18.9 Reading a Particular Line in a File
    Recipe 18.10 Processing a File Backward by Line or Paragraph
    Recipe 18.11 Picking a Random Line from a File
    Recipe 18.12 Randomizing All Lines in a File
    Recipe 18.13 Processing Variable Length Text Fields
    Recipe 18.14 Reading Configuration Files
    Recipe 18.15 Reading from or Writing to a Specific Location in a File
    Recipe 18.16 Removing the Last Line of a File
    Recipe 18.17 Modifying a File in Place Without a Temporary File
    Recipe 18.18 Flushing Output to a File
    Recipe 18.19 Writing to Standard Output
    Recipe 18.20 Writing to Many Filehandles Simultaneously
    Recipe 18.21 Escaping Shell Metacharacters
    Recipe 18.22 Passing Input to a Program
    Recipe 18.23 Reading Standard Output from a Program
    Recipe 18.24 Reading Standard Error from a Program
    Recipe 18.25 Locking a File
    Recipe 18.26 Reading and Writing Compressed Files
    Recipe 18.27 Program: Unzip
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele