Skip to content

Core\IO\File::close

$file->close(): void

Closes an open file. After close, the handle cannot be used any more.

$file->close() closes the Core\IO\File that Core\IO::open returned. Everything you wrote through the handle is in the file when close returns. A lock that the handle took with lock is released at the same time.

Calling close is optional. A handle that is still open when the request or the program ends is closed for you. Call close yourself when you are done with a file and the program continues, for example inside a loop that opens many files.

Every method you call on a closed handle throws a RuntimeError. This includes a second close. The error message names the method and the path of the file.

Return value

Returns void. Nothing.

Errors

  • RuntimeErrorThe handle has already been closed. Closing twice is a bug in the program, so it throws an error and is not ignored.

Examples

Close and read the file

<?nvs
// Shows how to write a file through a handle, close it, and then read the whole file.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'shopping.txt');
Core\IO\File $file = Core\IO::open($path, Core\IO::FileMode::Write);
$file->write("bread\n");
$file->write("milk\n");
// `close` closes the handle. The two lines are in the file now.
$file->close();
// This prints "bread" and "milk" on two lines.
echo Core\IO::readText($path);
Output
bread
milk

A closed handle throws

<?nvs
// Shows that a handle cannot be used after `close`, and that closing it twice throws an error.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'notes.txt');
Core\IO::write($path, "first note\n");
Core\IO\File $file = Core\IO::open($path, Core\IO::FileMode::Read);
$file->close();
// Reading from a closed handle throws a `RuntimeError`.
// This prints "read failed".
try {
$file->read(10);
} catch (RuntimeError $e) {
echo "read failed\n";
}
// A second `close` also throws a `RuntimeError`.
// This prints "close failed".
try {
$file->close();
} catch (RuntimeError $e) {
echo "close failed\n";
}
Output
read failed
close failed

Close in finally

<?nvs
// Shows how a program closes a file in `finally`, so the file is closed also when an error happens.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'prices.txt');
Core\IO::write($path, "12\n7\nfree\n30\n");
Core\IO\File $file = Core\IO::open($path, Core\IO::FileMode::Read);
int $total = 0;
try {
?string $line = $file->readLine();
while ($line != null) {
// `as int` throws a `RuntimeError` when the line is not a number.
$total = $total + ($line as int);
$line = $file->readLine();
}
} catch (RuntimeError $e) {
echo "stopped at a line that is not a number\n";
} finally {
// The code in `finally` runs in both cases, so the file is always closed here.
$file->close();
}
// This prints "total: 19", the sum of the lines before "free".
echo 'total: ', $total, "\n";
Output
stopped at a line that is not a number
total: 19