Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Dec 2006
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    reading a certain line from a .txt

    Alright I have a .TXT and I need to read the last and second to last line from the .txt file, how would I go about doing it?

    I have been searching on google/wiki/w3/forums/etc. for hours and can't find anything that works.

  • #2
    Senior Coder
    Join Date
    Jul 2005
    Location
    UK
    Posts
    1,051
    Thanks
    6
    Thanked 13 Times in 13 Posts
    No code but the basic idea would be:

    1. Read the file into an array using file()
    2. Count the number of elements in the array.
    3. Return the element that corresponds with the value of your count, and the value of your count-1.

    That should get you started.

  • #3
    New Coder
    Join Date
    Sep 2006
    Posts
    51
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Something like (for big files...)

    PHP Code:
    <?php

    // get the last two lines

    $get 2;

    // out container

    $out array_fill 1$get'' );

    // file starting position (feof + last \n)

    $pos = -2;

    // file to open

    $file 'junk.txt';

    // r+ so we can read and write if we need to, just r if reading only

    $io fopen $file'r+' );

    do
    {
        if ( 
    fseek $io$pos--, SEEK_END ) == -)
        {
            break;
        }
        else if ( ( 
    $chr fgetc $io ) ) == "\n" )
        {
            
    $get -= 1;
        }
        else
        {
            
    $out[$get] = $chr $out[$get];
        }

    } while ( 
    $get != );

    fclose $io );

    // just in case it windows rtrim (\r)

    $out array_map 'rtrim'$out );

    print_r $out );

    ?>

  • #4
    Super Moderator
    Join Date
    May 2005
    Location
    Southern tip of Silicon Valley
    Posts
    2,942
    Thanks
    2
    Thanked 169 Times in 164 Posts
    Here's something to look at for contrast/comparison.
    Code:
    #!/usr/bin/perl
    
    open (FILE, 'file.txt') || die $!;
    
    @last2lines = (<FILE>)[-2,-1];
    
    print @last2lines;


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •