Core\IO\File::write
Writes text to an open file.
$file->write($data) works on a Core\IO\File that Core\IO::open returned. It writes $data at the current position, and moves the position past it. The next write continues where this one stopped, so a program can write a large file in many small parts.
write returns the number of bytes it wrote. This is always the whole of $data, so the program never has to write the rest itself. A character such as é uses more than one byte, so the number can be larger than the number of characters. An empty string writes nothing and returns 0.
A closed handle throws a RuntimeError. A handle that can only read throws an IOError, and so does a write that fails, for example on a full disk.
Parameters
$datastring|bytesThe data to write, as astringor asbytes. It is written exactly as it is.
Return value
Returns uint. How many bytes were written. This is always every byte of $data. A partial write is retried until it is complete, so a caller never needs a loop.
Errors
RuntimeErrorThe handle has already been closed.IOErrorThe write itself failed, or the handle was not opened for writing.
Examples
Write a file in parts
<?nvs// Shows how to write a file in several parts through one open handle.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'greeting.txt');Core\IO\File $file = Core\IO::open($path, Core\IO::FileMode::Write);// Each `write` adds its text where the last one stopped.$file->write('Hello');$file->write(', ');$file->write("world\n");$file->close();
// This prints "Hello, world".echo Core\IO::read($path);Hello, worldThe result counts bytes
<?nvs// Shows what `write` returns: the number of bytes it wrote.// A character such as `é` or `ö` uses more than one byte.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'names.txt');Core\IO\File $file = Core\IO::open($path, Core\IO::FileMode::Write);
// "Café" has 4 characters and 5 bytes, so this prints 4 and then 5.echo Core\Str::length('Café'), "\n";echo $file->write('Café'), "\n";
// An empty string writes nothing, so the result is 0.echo $file->write(''), "\n";$file->close();450Export orders row by row
<?nvs// Shows how to export many rows to a CSV file one row at a time.// Only one row is in memory at a time, however many rows there are.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'orders.csv');Core\IO\File $out = Core\IO::open($path, Core\IO::FileMode::Write);uint $bytes = $out->write("id,customer,total\n");
uint $id = 1;while ($id <= 1000) { // This builds one row and writes it to the file. `write` returns its size in bytes. string $row = $id as string . ',Café Größenwahn,' . ($id * 3) as string . ".90\n"; $bytes = $bytes + $out->write($row); $id = $id + 1;}$out->close();
// This prints the number of bytes written, and that the file has that size.echo 'written: ', $bytes, " bytes\n";echo 'same size: ', Core\IO::size($path) == $bytes ? 'yes' : 'no', "\n";written: 30542 bytessame size: yes