Reputation: 45
I am trying to develop a small search engine application to search for my local files in my C:// directory by typing their names as input.
I received this suggestion as an implementation to the search function. However, it only allows me to search with the exact name of the file e.g "1234_0506AB.pdf"
I want my search function to take "1234" as an input and still be able to fetch "1234_0506AB.pdf".
Another suggestion was: instead of simply testing for equality via dir_entry.path().filename() == file_name
, just get the filename as string dir_entry.path().filename().string()
and do a .find()
. For even more general searching, you could use a regex and match that with the filename.
I have very little experience in that and require some help and guidance to use .find() or regex in my code.
#include <filesystem>
#include <algorithm>
namespace fs = std::filesystem;
void search(const fs::path& directory, const fs::path& file_name)
{
auto d = fs::directory_iterator(directory);
auto found = std::find_if(d, end(d), [&file_name](const auto& dir_entry)
{
return dir_entry.path().filename() == file_name;
});
if (found != end(d))
{
// we have found what we were looking for
}
// ...
}
Upvotes: 1
Views: 5291
Reputation: 5668
To use find, you should check the documentation of the method, which also contains some examples on most sites.
In your code, you accept a filename if its exactly the same as the one you are looking for:
return dir_entry.path().filename() == file_name;
To accept substring matches, you'll have to modify this check to use find
instead of ==
. As mentioned in the linked doc, find
returns npos
if it can't find a match.
return dir_entry.path().filename().string().find(file_name.string()) != std::string::npos;
If you are looking for matches only at the beginning of the string, you could use == 0
instead of != npos
.
But in this case, you have other options too, for example using substr to cut the filename to the desired length:
return dir_entry.path().filename().string().substr(0, file_name.size()) == file_name.string();
For a solution using regex, check the regex examples on the same site.
Upvotes: 4