Binary Reading: fread


Binary Reading: fread

You don't have to read data from files line by line; you can read as much or as little as you want with the fread function. The fgets function treats files as text, but fread TReats files as binary files, making no guesses as to where lines end or performing other interpretationthe file is just treated as a simple binary file of bytes. Here's how you use fread in general:

 fread (resource handle, int length) 

This function reads up to length bytes from the file pointer referenced by handle. Reading stops when length bytes have been read or when the EOF (end of file) is reached.

On systems like Windows, you should open files for binary reading (mode 'rb') to work with fread. Because adding 'b' to the mode does no harm on other systems, we'll include it here for portability:

 <?php     $handle = fopen("file.txt", "rb");         .         .         . ?> 

Using fread, you can read a whole file into a string by asking fread to read the number of bytes corresponding to the file's length, which you can find with the filesize function:

 <?php     $handle = fopen("file.txt", "rb");     $text = fread($handle, filesize("file.txt"));         .         .         . ?> 

This reads the entire file into $text if there wasn't an error, which you can check by making sure $text doesn't hold an empty string. To convert line endings in the text into <BR> elements, we'll use the str_replace function:

 <?php     $handle = fopen("file.txt", "rb");     $text = fread($handle, filesize("file.txt"));     $br_text = str_replace("\n", "<BR>", $text);         .         .         . ?> 

All that's left is to echo the HTML-prepared text to the browser window and close the file, as you see in phpread.php, Example 7-8.

Example 7-8. Using fread, phpread.php
 <HTML>     <HEAD>         <TITLE>             Reading a file with fread         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Reading a file with fread             </H1>             <?php                 $handle = fopen("file.txt", "rb");                 $text = fread($handle, filesize("file.txt"));                 $br_text = str_replace("\n", "<BR>", $text);                 echo $br_text;                 fclose($handle);             ?>         </CENTER>     </BODY> </HTML> 

The results appear in Figure 7-8, where we've read and displayed the file. Not bad.

Figure 7-8. Reading from a file using fread.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net