| 601 | } |
| 602 | |
| 603 | SC::Result snippetForFileRead(AsyncEventLoop& eventLoop, Console& console) |
| 604 | { |
| 605 | ThreadPool threadPool; |
| 606 | SC_TRY(threadPool.create(4)); |
| 607 | //! [AsyncFileReadSnippet] |
| 608 | // Assuming an already created (and running) AsyncEventLoop named `eventLoop` |
| 609 | // ... |
| 610 | |
| 611 | // Assuming an already created threadPool named `threadPool` |
| 612 | // ... |
| 613 | |
| 614 | // Open the file |
| 615 | FileDescriptor fd; |
| 616 | FileOpen openMode; |
| 617 | openMode.mode = FileOpen::Read; |
| 618 | openMode.blocking = true; // AsyncFileRead::Task enables using regular blocking file descriptors |
| 619 | SC_TRY(fd.open("MyFile.txt", openMode)); |
| 620 | |
| 621 | // Create the async file read request and async task |
| 622 | AsyncFileRead asyncReadFile; |
| 623 | asyncReadFile.callback = [&](AsyncFileRead::Result& res) |
| 624 | { |
| 625 | Span<char> readData; |
| 626 | if(res.get(readData)) |
| 627 | { |
| 628 | if(res.completionData.endOfFile) |
| 629 | { |
| 630 | // Last callback invocation done when end of file has been reached |
| 631 | // - completionData.endOfFile is == true |
| 632 | // - readData.sizeInBytes() is == 0 |
| 633 | console.print("End of file reached"); |
| 634 | } |
| 635 | else |
| 636 | { |
| 637 | // readData is a slice of receivedData with the received bytes |
| 638 | console.print("Read {} bytes from file", readData.sizeInBytes()); |
| 639 | |
| 640 | // OPTIONAL: Update file offset to receive a different range of bytes |
| 641 | res.getAsync().setOffset(res.getAsync().getOffset() + readData.sizeInBytes()); |
| 642 | |
| 643 | // IMPORTANT: Reactivate the request to receive more data |
| 644 | res.reactivateRequest(true); |
| 645 | } |
| 646 | } |
| 647 | else |
| 648 | { |
| 649 | // Some error occurred, check res.returnCode |
| 650 | } |
| 651 | }; |
| 652 | char buffer[100] = {0}; |
| 653 | asyncReadFile.buffer = {buffer, sizeof(buffer)}; |
| 654 | // Obtain file descriptor handle and associate it with event loop |
| 655 | SC_TRY(fd.get(asyncReadFile.handle, Result::Error("Invalid handle"))); |
| 656 | |
| 657 | // Start the operation on a thread pool |
| 658 | AsyncTaskSequence asyncFileTask; |
| 659 | SC_TRY(asyncReadFile.executeOn(asyncFileTask, threadPool)); |
| 660 | SC_TRY(asyncReadFile.start(eventLoop)); |