Best way to check if file abc* exists in a particular directory in C++

I have a specific problem at my hand right now. I have core* files in my /tmp/ folder on linux.

I want to know how to check if the file core* exists in /tmp/ path. The actual file can be anything like below. * corexyz.txt * coreabc.tar.gz * core*

Please provide your valuable answers.

If the complete file name was known, I could have used stat or access to know if the file existed. But here, I want to know if there is any file with core*.

bool checkFile (std::string ABC)
{
/* Check if the file abc* exists */
return true; /* return true if file ABC* exists */
}
Last edited on
Iterate over all files in the directory.
Check if filename begin with "core".
Maybe like this?
1
2
3
4
5
6
7
8
bool contains_core_file(std::filesystem::path const& p)
{
  auto is_core_file = [re = std::regex{R"(core.*)"}] (auto const& dirent)
    { return std::regex_match(dirent.path().filename().string(), re); };
      
  return std::any_of
    (std::filesystem::recursive_directory_iterator{p}, {}, is_core_file);
}
Must you do it in C++? It's trivial with the shell
1
2
3
4
5
$ if ls abc* > /dev/null ; then
> echo yes
> else
> echo no
> fi

Topic archived. No new replies allowed.