read method

  1. @override
Future<int> read(
  1. List<int> cbuf, [
  2. int offset = 0,
  3. int? length
])
override

Reads characters into an array.

This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.

Parameters

  • cbuf: Destination buffer
  • offset: Offset at which to start storing characters (default: 0)
  • length: Maximum number of characters to read (default: remaining buffer space)

Returns

The number of characters read, or -1 if the end of the stream has been reached.

Example

final reader = FileReader('text.txt');
try {
  final buffer = List<int>.filled(1024, 0);
  final charsRead = await reader.read(buffer);
  if (charsRead != -1) {
    final text = String.fromCharCodes(buffer.sublist(0, charsRead));
    print('Read: $text');
  }
} finally {
  await reader.close();
}

Throws InvalidArgumentException if offset or length is negative, or if offset + length is greater than the length of cbuf. Throws IOException if an I/O error occurs. Throws StreamClosedException if the reader has been closed.

Implementation

@override
Future<int> read(List<int> cbuf, [int offset = 0, int? length]) async {
  length ??= cbuf.length - offset;

  if (offset < 0 || length < 0 || offset + length > cbuf.length) {
    throw InvalidArgumentException('Invalid offset or length');
  }

  if (length == 0) {
    return 0;
  }

  await _ensureOpen();

  if (_buffer == null || _bufferPosition >= _buffer!.length) {
    return -1; // End of file
  }

  final availableChars = _buffer!.length - _bufferPosition;
  final charsToRead = length.clamp(0, availableChars);

  for (int i = 0; i < charsToRead; i++) {
    cbuf[offset + i] = _buffer!.codeUnitAt(_bufferPosition + i);
  }

  _bufferPosition += charsToRead;
  return charsToRead;
}