Specifications
It is not generally sensible to read a file character-by-character unless for some reason we want
to process it character-by-character.
Reading an Arbitrary Length: fread()
The final way we can read from a file is using the fread() function to read an arbitrary num-
ber of bytes from the file. This function has the following prototype:
string fread(int fp, int length);
The way it works is to read up to length bytes or to the end of file, whichever comes first.
Other Useful File Functions
There are a number of other file functions we can use that are useful from time-to-time.
Checking Whether a File Is There: file_exists()
If you want to check if a file exists without actually opening it, you can use file_exists(),as
follows:
if (file_exists(“$DOCUMENT_ROOT/../orders/orders.txt”))
echo “There are orders waiting to be processed.”;
else
echo “There are currently no orders.”;
Knowing How Big a File Is: filesize()
You can check the size of a file with the filesize() function. It returns the size of a file in
bytes:
echo filesize(“$DOCUMENT_ROOT/../orders/orders.txt”);
It can be used in conjunction with fread() to read a whole file (or some fraction of the file) at
a time. We can replace our entire original script with
$fp = fopen(“$DOCUMENT_ROOT/../orders/orders.txt”, “r”);
echo fread( $fp, filesize(“$DOCUMENT_ROOT/../orders/orders.txt” ));
fclose( $fp );
Deleting a File: unlink()
If you want to delete the order file after the orders have been processed, you can do it using
unlink(). (There is no function called delete.) For example
unlink(“$DOCUMENT_ROOT/../orders/orders.txt”);
This function returns false if the file could not be deleted. This will typically occur if the per-
missions on the file are insufficient or if the file does not exist.
Storing and Retrieving Data
C
HAPTER 2
2
STORING AND
RETRIEVING DATA
63
04 7842 CH02 3/6/01 3:37 PM Page 63