# read method

Future<int> read(

1. List<int> b, [
2. int offset = 0,
3. int? length

])

Reads some number of bytes from the input stream and stores them into the buffer array `b`.

The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.

If the length of `b` is zero, then no bytes are read and `0` is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at the end of the file, the value `-1` is returned; otherwise, at least one byte is read and stored into `b`.

## Parameters

- `b`: The buffer into which the data is read
- `offset`: The start offset in array `b` at which the data is written
- `length`: The maximum number of bytes to read

## Returns

The total number of bytes read into the buffer, or `-1` if there is no more data because the end of the stream has been reached.

## Example

    final input = FileInputStream('data.bin');
    final buffer = Uint8List(1024);

    // Read up to 1024 bytes
    final bytesRead = await input.read(buffer);
    if (bytesRead != -1) {
      print('Read $bytesRead bytes');
      processData(buffer.sublist(0, bytesRead));
    }

    // Read into a specific portion of the buffer
    final partialRead = await input.read(buffer, 100, 500);
    await input.close();

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

## Implementation

    Future<int> read(List<int> b, [int offset = 0, int? length]) async {
      checkClosed();

      length ??= b.length - offset;

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

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

      final firstByte = await readByte();
      if (firstByte == -1) {
        return -1;
      }

      b[offset] = firstByte;
      int bytesRead = 1;

      try {
        for (int i = 1; i < length; i++) {
          final byte = await readByte();
          if (byte == -1) {
            break;
          }
          b[offset + i] = byte;
          bytesRead++;
        }
      } catch (e) {
        // Return what we've read so far
      }

      return bytesRead;
    }