Reading and writing files

 
 
 

The fopen, fwrite, fprint, fread, and fclose commands let you work with files.

Opening a file

Before you can read from or write to a file, you need to open the file using the fopen function.

fopen takes two string arguments:

fopen returns a file handle. The file handle represents the open file. You should save this value in a variable so you can work with the open file using other commands such as fprint.

$fileId = fopen($exampleFileName,"r");

Reading from a file

Once you have opened a file to read, you can actually read data from the file using one of the following commands:

To... Use this command

Read a line (read to the next newline).

fgetline (fileID)

Read a word (read to the next whitespace).

fgetword (fileID)

Read a single value.

fread (fileID, type)

For example:

// Read a file one line at a time
$fileId=fopen($exampleFileName,"r");
string $nextLine = `fgetline $fileId`;
while ( size( $nextLine ) > 0 ) {
	print ( $nextLine );
	$nextLine = `fgetline $fileId`;
}

Testing for the end of the file

The feof <fileID> function returns non-zero if you are at the end of the file.

string $nextWord = `fgetword $fileId`;
while ( !feof($fileId) ) {
 	print ( $nextWord + "\n" );
 	$nextWord = fgetword($fileId);
}

If an empty file is opened, feof will not detect that it is at the end of the file until at least one read is performed.

Writing to a file

Once you have opened a file to write or append, you can actually write data to the file using one of the following commands:

To... Use this command

Print to the file using an equivalent to the print command.

fprint (fileID,string)

Write binary data.

fwrite (fileID, value)

For example:

$fileId = fopen($exampleFileName,"w");
fprint($fileId,"Hello there\n");
fclose($fileId);

The fwrite command writes the data argument in binary format to a file. It writes strings as ASCII terminating with a NULL character. You should not use fwrite for writing to a text file or for writing raw bytes unless you want a NULL character on the end.

Managing an open file

To flush the write buffer without closing the file, use fflush(fileID).

To reset the file position pointer to the beginning of the file, use frewind(fileID).

Closing an open file

To close an open file, use fclose(fileID).

Creative Commons License Except where otherwise noted, this work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License