Wikis & learning

Summarize a text file using a stream

Streams provide a common way to read data from files and other sources. The temporary stream in this exercise behaves like a file while keeping the lesson self-contained.

Streams provide a common way to read data from files and other sources. The temporary stream in this exercise behaves like a file while keeping the lesson self-contained.

Walkthrough

After writing, rewind to the beginning before reading. The loop distinguishes end of input from a line containing the character zero. Close the handle as soon as the task is finished.

PHP example

<?php
$handle = fopen('php://temp', 'w+');
fwrite($handle, "oak\nash\n0\n");
rewind($handle);
$count = 0;
while (($line = fgets($handle)) !== false) {
    $count++;
}
fclose($handle);
echo $count, ' lines';

Expected output

3 lines

Change and check

Add an empty line and a line containing just zero. Count all physical lines first, then modify the loop to count only nonblank lines.