tailFile function

Future<ReadFileRangeResult> tailFile(
  1. String path,
  2. int maxBytes
)

Read the last maxBytes of a file. Returns the whole file if it's smaller than maxBytes.

Implementation

Future<ReadFileRangeResult> tailFile(String path, int maxBytes) async {
  final raf = await File(path).open(mode: FileMode.read);
  try {
    final size = await raf.length();
    if (size == 0) {
      return ReadFileRangeResult(content: '', bytesRead: 0, bytesTotal: 0);
    }
    final offset = max(0, size - maxBytes);
    final bytesToRead = size - offset;
    final buffer = Uint8List(bytesToRead);
    await raf.setPosition(offset);

    int totalRead = 0;
    while (totalRead < bytesToRead) {
      final bytesRead = await raf.readInto(buffer, totalRead, bytesToRead);
      if (bytesRead == 0) break;
      totalRead += bytesRead;
    }

    return ReadFileRangeResult(
      content: String.fromCharCodes(buffer, 0, totalRead),
      bytesRead: totalRead,
      bytesTotal: size,
    );
  } finally {
    await raf.close();
  }
}