Pure async function for fs io without callbacks

dev-own-engine
marcelb 8 months ago
parent daec3d7f00
commit dc02778445
  1. 47
      lib/filesystem.hpp
  2. 19
      test/test.cpp

@ -12,7 +12,7 @@ using namespace std;
namespace marcelb { namespace marcelb {
/** /**
* Asynchronous file reading * Asynchronous file reading with callback after read complete
*/ */
template<typename Callback> template<typename Callback>
void asynco_read(string path, Callback&& callback) { void asynco_read(string path, Callback&& callback) {
@ -40,8 +40,32 @@ void asynco_read(string path, Callback&& callback) {
}); });
} }
/**
* Asynchronous file reading
*/
future<string> 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<typename Callback> template<typename Callback>
void asynco_write(string path, string content, Callback&& callback) { 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<void> 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 #endif

@ -275,7 +275,7 @@ int main () {
// cout << "Constructed " << i << endl; // cout << "Constructed " << i << endl;
// }); // });
// string data_; string data_;
// asynco_read("test.txt", [&data_] (string data, exception* error) { // asynco_read("test.txt", [&data_] (string data, exception* error) {
// if (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) { // asynco_write("test1.txt", "Hello night", [] (exception* error) {
// if (error) { // if (error) {
// cout << "Error " << error->what() << endl; // 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; cout << "Sleep" << endl;
sleep(100000); // only for testing sleep(100000); // only for testing

Loading…
Cancel
Save