Skip to content

Instantly share code, notes, and snippets.

@utilForever
Last active April 25, 2016 09:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save utilForever/bbc84e4591926b09036ce29745dfa74e to your computer and use it in GitHub Desktop.
Save utilForever/bbc84e4591926b09036ce29745dfa74e to your computer and use it in GitHub Desktop.
Search files that matches specific word in certain directory (C++17)
#include <experimental\filesystem>
#include <iostream>
#include <fstream>
using namespace std;
using namespace std::experimental::filesystem;
int main(int argc, char* argv[])
{
if (argc < 2)
{
cout << "Usage: Test path\n";
return 1;
}
path p(argv[1]);
try
{
if (exists(p))
{
if (is_regular_file(p))
cout << p << " size is " << file_size(p) << '\n';
else if (is_directory(p))
{
cout << p << " is a directory containing:\n";
std::vector<std::string> v;
for (auto&& x : directory_iterator(p))
{
ifstream fileInput;
string line;
char* search = "Test";
fileInput.open(x.path().string());
if (fileInput.is_open())
{
while (getline(fileInput, line))
{
if (line.find(search, 0) != string::npos) {
v.push_back(x.path().filename().string());
break;
}
}
}
fileInput.close();
}
std::sort(v.begin(), v.end());
for (auto&& x : v)
cout << " " << x << '\n';
}
else
cout << p << " exists, but is not a regular file or directory\n";
}
else
cout << p << " does not exist\n";
}
catch (const filesystem_error& ex)
{
cout << ex.what() << '\n';
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment