MCPcopy Create free account
hub / github.com/Pagghiu/SaneCppLibraries / snippetForFileRead

Function snippetForFileRead

Tests/Libraries/Async/AsyncTest.cpp:603–669  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

601}
602
603SC::Result snippetForFileRead(AsyncEventLoop& eventLoop, Console& console)
604{
605ThreadPool threadPool;
606SC_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
615FileDescriptor fd;
616FileOpen openMode;
617openMode.mode = FileOpen::Read;
618openMode.blocking = true; // AsyncFileRead::Task enables using regular blocking file descriptors
619SC_TRY(fd.open("MyFile.txt", openMode));
620
621// Create the async file read request and async task
622AsyncFileRead asyncReadFile;
623asyncReadFile.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};
652char buffer[100] = {0};
653asyncReadFile.buffer = {buffer, sizeof(buffer)};
654// Obtain file descriptor handle and associate it with event loop
655SC_TRY(fd.get(asyncReadFile.handle, Result::Error("Invalid handle")));
656
657// Start the operation on a thread pool
658AsyncTaskSequence asyncFileTask;
659SC_TRY(asyncReadFile.executeOn(asyncFileTask, threadPool));
660SC_TRY(asyncReadFile.start(eventLoop));

Callers

nothing calls this directly

Calls 11

printMethod · 0.80
reactivateRequestMethod · 0.80
executeOnMethod · 0.80
ErrorEnum · 0.50
ResultClass · 0.50
createMethod · 0.45
openMethod · 0.45
getMethod · 0.45
sizeInBytesMethod · 0.45
startMethod · 0.45
runMethod · 0.45

Tested by

no test coverage detected