Skip to content

Core\IO\Lines

The lines of a file, which Core\IO::lines returns. Use it in a foreach loop. Each step reads the file up to the next line ending and gives that line as a string. A second loop over the same value goes on where the first one stopped.

Core\IO\Lines gives the lines of a text file. Core\IO::lines returns it. The class has no methods. You read it with a foreach loop.

Each item is a string with one line, without its line break. A line ends at \n, \r\n or a single \r. An empty line in the middle of the file is an empty string. A line break at the end of the file does not add an empty last line.

Core\IO::lines opens the file when you call it. The loop reads the file one line at a time, so a file larger than the memory limit can be read. A break stops the reading. The file is closed at the end of the file, or when your program no longer uses the result. A second loop over the same result goes on where the first loop stopped. Call Core\IO::lines again to start from the first line.

Core\IO::lines throws an IOError when the file does not exist or cannot be opened. It throws a RuntimeError when the program may not read the path. A line that is not valid UTF-8 text throws a RuntimeError inside the loop, when the loop reaches that line. The lines before it are already read.

buy milk
call the bank
water the plants
<?nvs
var $lines = Core\IO::lines('todo.txt');
uint $number = 0;
foreach ($lines as string $line) {
$number = $number + 1;
echo $number, ': ', $line, "\n";
if ($number == 2) {
break;
}
}
// The second loop goes on with the third line.
foreach ($lines as string $line) {
echo 'later: ', $line, "\n";
}
Output
1: buy milk
2: call the bank
later: water the plants

Returned by

You get a Core\IO\Lines from these methods: