PHP - Reading and Writing Strings of Characters

Introduction

The fread() function can read a string of characters from a file.

It takes two arguments: a file handle and the number of characters to read.

The function reads the specified number of characters or less if the end of the file is reached and returns them as a string.

For example:

$handle = fopen("data.txt" ,"r" );
$data = fread($handle, 10);

This code reads the first ten characters from data.txt and assigns them to $data as a string.

When working with binary files a character is always one byte long, so ten characters equals ten bytes.

If there are less than ten characters left to read in the file, fread() simply reads and returns as many as there are.

By the way, if you want to read only one character at a time you can use the fgetc() function.

fgetc() takes a single argument - a file handle - and returns just one character from the file it points to; it returns false when it reaches the end of the file:

$one_char = fgetc($handle);

You can use the fwrite() function to write data to a file.

It requires two arguments: a file handle and a string to write to the file.

The function writes the contents of the string to the file, returning the number of characters written or false if there's an error.

For example:

$handle = fopen("data.txt" ," w" );
fwrite($handle,"ABCxyz" );

The first line opens the file data.txt for writing, which erases any existing data in the file.

The second line writes the character string "ABCxyz" to the beginning of the file.

You can limit the number of characters written by specifying an integer as a third argument.

The function stops writing after that many characters.

For example, the following code writes the first four characters of "abcd" to the file:

fwrite($handle,"abcdefghij" , 4);

Related Topic