/////////////////////////////////////////////////////////////////////// // MT2Q4.cpp - Asynchronous text finder // // // // Jim Fawcett, CSE687 - Object Oriented Design, Midterm Spring 2018 // /////////////////////////////////////////////////////////////////////// #include "MT2Q4.h" #include "../StringUtilities/StringUtilities.h" #include //----< synchronous text finder >-------------------------------------- bool MT2Q4::findText(const std::string& text, const std::string& filePath) { std::ifstream in(filePath); if (!in.good()) { std::cout << "\n can't open \"" << filePath << "\""; return false; } std::string fileText; while (in.good()) { char ch; in >> ch; if(ch != '\n') // text may span multiple lines fileText += ch; } size_t pos = fileText.find(text); return pos < fileText.size(); } //----< run finder asynchronously >------------------------------------ std::future MT2Q4::findTextAsync(FPtr finder, const std::string& text, const std::string& filePath) { return std::async(finder, text, filePath); /////////////////////////////////////////////////////////////// // if you want to implement the whole thing, here's how: // // std::promise prm; // std::future fut(prm.get_future()); // auto lambda = [finder](const std::string& text, const std::string& filePath, std::promise p) { // bool ret = pFinder(text, filePath); // p.set_value(ret); // }; // std::thread t(lambda, text, filePath, std::move(prm)); // t.detach(); // return fut; } int main() { Utilities::Title("MT2Q4 - text finder"); MT2Q4 mt2q4; std::string text = "main"; std::string fPath1 = "../Test/Copy_MT2Q4.h"; std::string fPath2 = "../Test/Copy_MT2Q4.cpp"; std::future f1 = mt2q4.findTextAsync(MT2Q4::findText, text, fPath1); std::future f2 = mt2q4.findTextAsync(MT2Q4::findText, text, fPath2); if (f1.get()) std::cout << "\n found \"" << text << "\" in file \"" << fPath1; else std::cout << "\n didn't find \"" << text << "\" in file \"" << fPath1; if (f2.get()) std::cout << "\n found \"" << text << "\" in file \"" << fPath2; else std::cout << "\n didn't find \"" << text << "\" in file \"" << fPath2; std::cout << "\n\n"; return 0; }