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

Function snippetForFileWrite

Tests/Libraries/Async/AsyncTest.cpp:672–724  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

670
671
672SC::Result snippetForFileWrite(AsyncEventLoop& eventLoop, Console& console)
673{
674ThreadPool threadPool;
675SC_TRY(threadPool.create(4));
676//! [AsyncFileWriteSnippet]
677// Assuming an already created (and running) AsyncEventLoop named `eventLoop`
678// ...
679
680// Assuming an already created threadPool named `threadPool`
681// ...
682
683// Open the file (for write)
684FileOpen openMode;
685openMode.mode = FileOpen::Write;
686openMode.blocking = true; // AsyncFileWrite::Task enables using regular blocking file descriptors
687FileDescriptor fd;
688SC_TRY(fd.open("MyFile.txt", openMode));
689
690// Create the async file write request
691AsyncFileWrite asyncWriteFile;
692asyncWriteFile.callback = [&](AsyncFileWrite::Result& res)
693{
694 size_t writtenBytes = 0;
695 if(res.get(writtenBytes))
696 {
697 console.print("{} bytes have been written", writtenBytes);
698 }
699};
700// Obtain file descriptor handle
701SC_TRY(fd.get(asyncWriteFile.handle, Result::Error("Invalid Handle")));
702asyncWriteFile.buffer = StringView("test").toCharSpan();
703// Vectorized writes: use proper start overload or set
704// AsyncFileWrite::buffers and AsyncFileWrite::singleBuffer = false
705
706// Start the operation in a thread pool
707AsyncTaskSequence asyncFileTask;
708SC_TRY(asyncWriteFile.executeOn(asyncFileTask, threadPool));
709SC_TRY(asyncWriteFile.start(eventLoop));
710
711// Execute another file write AFTER the previous one is finished on the same threadPool
712AsyncFileWrite asyncWriteFileLater;
713asyncWriteFileLater.buffer = StringView("AFTER").toCharSpan();
714SC_TRY(asyncWriteFileLater.executeOn(asyncFileTask, threadPool));
715SC_TRY(asyncWriteFile.start(eventLoop));
716
717// Alternatively if the file is opened with blocking == false, AsyncFileRead can be omitted
718// but the operation will not be fully async on regular (buffered) files, except on io_uring.
719//
720// SC_TRY(asyncWriteFile.start(eventLoop));
721//! [AsyncFileWriteSnippet]
722SC_TRY(eventLoop.run());
723return Result(true);
724}
725
726// clang-format on
727} // namespace SC

Callers

nothing calls this directly

Calls 9

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

Tested by

no test coverage detected