Back to DFS's Workshop Page
Back to Agenda Page


Files II

Most of the time you will not know how many lines there are in a file. This page will show you a way of handling this situation.

  1. Create a new file in the ~YOURID/PHP/ directory by executing the following from the Command Line.

    cd; cd PHP; ls -l > dir_list.dat
    This will get you into the desired directory and create a file called dir_list.dat which will contain the long version of the directory listing.

  2. Create the following script in the same directory.

    <?php
    // listfile.php
    // Purpose: read all lines from a file
    //     and print them
    
    // Open the file for reading 
    $fp = fopen( "dir_list.dat", "r") or die("No such file!\n");
    
    // Read lines one by one, printing each out in turn
    while ( !feof($fp) ) {
       $str = fgets( $fp, 500);
       echo $str;
    }
    
    // Close the file
    fclose($fp);
    ?>
    

  3. Run the script. The output should be the same if you execute the following on the Command Line.

    cat dir_list.dat

Notes


© 2002-2005 DFStermole
Created: 22 Sept 02
Last Modified: 31 July 05