Skip to content

Core\IO::lines

Reads a text file one line at a time.

Core\IO::lines opens the file when you call it. Each step of a foreach loop reads one line, so a file larger than the memory limit can be read. Each line comes without its line break. A line ends at \n, at \r\n or at a single \r. A line break at the end of the file does not add an empty last line.

lines returns a Core\IO\Lines value. After a break, a second loop over it starts at the line after the last one the first loop read. The file is closed after its last line or at an error. It is also closed when no variable refers to the value any more.

lines throws an IOError when the file does not exist or cannot be opened. A line that is not valid UTF-8 text throws an error inside the loop, at that line.

On a server, a program may read only the files in its application folder, except nvs.toml and names that start with .. Any other path needs the fs.read capability. Without it, lines throws a RuntimeError.

Parameters

  • $pathstringThe file to read. A relative path must be a string written directly in the code. It is joined to the folder of the file that contains it.

Return value

Returns Core\IO\Lines. A Core\IO\Lines. A foreach loop gives the lines in file order. After a break, a second loop continues with the next line. \n, \r\n and a single \r each end a line. A line ending at the end of the file does not add an empty last line. An empty file has no lines. The file is closed at the end of the loop, or when the program no longer uses the value.

Errors

  • RuntimeErrorThe configuration does not grant fs.read for this path. The loop also throws this error at a line that is not valid UTF-8. The loop has already given every line before it.
  • IOErrorThe capability allowed the call, but the operating system did not. The file does not exist or could not be opened. Inside the loop: the file could not be read, or it is a directory.

Changelog

VersionChange
0.0.6Core\IO::lines reads one line per step of the foreach loop, so a file larger than the memory limit can be read. A line that is not valid UTF-8 throws an error inside the loop, at that line. A second loop goes on where the first loop stopped.

Examples

Number each line

<?nvs
// Shows how to loop over the lines that `Core\IO::lines` reads from a file.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'todo.txt');
Core\IO::write($path, "buy milk\ncall the bank\nwater the plants\n");
// Each line comes without its line break. The last line break does not add an empty line.
// This prints "1: buy milk", "2: call the bank" and "3: water the plants".
uint $number = 0;
foreach (Core\IO::lines($path) as string $line) {
$number = $number + 1;
echo $number, ': ', $line, "\n";
}
Output
1: buy milk
2: call the bank
3: water the plants

Line endings

<?nvs
// Shows that `Core\IO::lines` reads Windows, Linux and old Mac line breaks the same way.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'colors.txt');
// The first text uses "\r\n" (Windows). The second uses "\n" (Linux and macOS).
// The third uses "\r" (old Mac). Each text has the same three lines.
array<string> $contents = ["red\r\ngreen\r\nblue\r\n", "red\ngreen\nblue\n", "red\rgreen\rblue"];
// This prints "red|green|blue" three times.
foreach ($contents as string $content) {
Core\IO::write($path, $content);
array<string> $found = [];
foreach (Core\IO::lines($path) as string $line) {
$found[] = $line;
}
echo Core\Str::join($found, '|'), "\n";
}
// An empty line in the middle is kept. An empty file has no lines at all.
// This prints "lines: 3" and then "lines: 0".
array<string> $texts = ["a\n\nb\n", ''];
foreach ($texts as string $text) {
Core\IO::write($path, $text);
uint $count = 0;
foreach (Core\IO::lines($path) as string $line) {
$count = $count + 1;
}
echo 'lines: ', $count, "\n";
}
Output
red|green|blue
red|green|blue
red|green|blue
lines: 3
lines: 0

Read a settings file

<?nvs
// Shows how a program reads a settings file with one `name=value` pair on each line.
class Settings
{
// Returns the settings in the file as an array. Each key is a name, and each value is its value.
// Empty lines and lines that start with "#" are skipped.
public static function load(string $path): array<string>
{
array<string> $settings = [];
foreach (Core\IO::lines($path) as string $line) {
string $clean = Core\Str::trim($line);
if ($clean == '' || Core\Str::startsWith($clean, '#')) {
continue;
}
array<string> $parts = Core\Str::split($clean, '=', { limit: 2 });
$settings[Core\Str::trim($parts[0])] = Core\Str::trim($parts[1]);
}
return $settings;
}
}
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'app.env');
Core\IO::write($path, "# Database\nDB_HOST = localhost\nDB_PORT = 5432\n\n# Mail\nMAIL_FROM = shop@example.com\n");
// This prints "DB_HOST: localhost", "DB_PORT: 5432" and "MAIL_FROM: shop@example.com".
foreach (Settings::load($path) as string $name => string $value) {
echo $name, ': ', $value, "\n";
}
Output
DB_HOST: localhost
DB_PORT: 5432
MAIL_FROM: shop@example.com