From dc02778445c5e3b3301e0e5741b8338d59033faf Mon Sep 17 00:00:00 2001 From: marcelb Date: Sun, 24 Mar 2024 10:02:13 +0100 Subject: [PATCH] Pure async function for fs io without callbacks --- lib/filesystem.hpp | 47 ++++++++++++++++++++++++++++++++++++++++++++-- test/test.cpp | 19 ++++++++++++++++++- 2 files changed, 63 insertions(+), 3 deletions(-) diff --git a/lib/filesystem.hpp b/lib/filesystem.hpp index a0be8a3..6801d79 100644 --- a/lib/filesystem.hpp +++ b/lib/filesystem.hpp @@ -12,7 +12,7 @@ using namespace std; namespace marcelb { /** - * Asynchronous file reading + * Asynchronous file reading with callback after read complete */ template void asynco_read(string path, Callback&& callback) { @@ -40,8 +40,32 @@ void asynco_read(string path, Callback&& callback) { }); } + +/** + * Asynchronous file reading +*/ +future asynco_read(string path) { + return asynco( [&path] () { + string content; + string line; + ifstream file (path); + if (file.is_open()) { + line.clear(); + while ( getline (file,line) ) { + content += line + "\n"; + } + file.close(); + return content; + } + + else { + throw runtime_error("Unable to open file"); + } + }); +} + /** - * Asynchronous file writing + * Asynchronous file writing with callback after write complete */ template void asynco_write(string path, string content, Callback&& callback) { @@ -63,6 +87,25 @@ void asynco_write(string path, string content, Callback&& callback) { }); } + +/** + * Asynchronous file writing with callback after write complete +*/ +future asynco_write(string path, string content) { + return asynco( [&path, &content] () { + ofstream file (path); + if (file.is_open()) { + file << content; + file.close(); + return; + } + else { + throw runtime_error("Unable to open file"); + } + }); +} + + } #endif \ No newline at end of file diff --git a/test/test.cpp b/test/test.cpp index f5d1820..f15f7c7 100644 --- a/test/test.cpp +++ b/test/test.cpp @@ -275,7 +275,7 @@ int main () { // cout << "Constructed " << i << endl; // }); - // string data_; + string data_; // asynco_read("test.txt", [&data_] (string data, exception* error) { // if (error) { @@ -287,6 +287,15 @@ int main () { // } // }); + // auto data = asynco_read("test4.txt"); + + // try { + // data_ = wait(data); + // cout << "data" << data_ << endl; + // } catch (exception& err) { + // cout << err.what() << endl; + // } + // asynco_write("test1.txt", "Hello night", [] (exception* error) { // if (error) { // cout << "Error " << error->what() << endl; @@ -295,6 +304,14 @@ int main () { // } // }); + auto status = asynco_write("test1.txt", "Hello night"); + + + // try { + // wait(status); + // } catch (exception& err) { + // cout << err.what() << endl; + // } cout << "Sleep" << endl; sleep(100000); // only for testing