1

I'm trying to get all of the file with a certain pattern from a specific directory.
for example "ia_aiq_usecase_*.bin" from "c:\temp"

my windows code works fine. however in linux I do not want to use boost. and I can't seem to find a way to get all the files with a certain pattern.
Can you please help ?

Is there a way to do it cross platform?

const std::vector<std::string> OS::GetAllFiles(std::string directoryPath, std::string filePattern)
{
#ifdef _WIN32
    std::vector<std::string> files;
    std::string pathAndPattern = directoryPath + OS::PathSeperator() + filePattern;
    WIN32_FIND_DATA fd;
    HANDLE hFind = ::FindFirstFile(ToWString(pathAndPattern).c_str(), &fd);
    if (hFind != INVALID_HANDLE_VALUE) 
     {
        do
        {
            if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
            {
                files.push_back(FromWString(fd.cFileName));
            }
        } 
        while (::FindNextFile(hFind, &fd));
        {
            ::FindClose(hFind);
        }
    }
    return files;
#else
    std::vector<std::string> files;
    std::string search_path = directoryPath + OS::PathSeperator() + filePattern;
    DIR *dp;
    struct dirent *dirp;
    if ((dp = opendir(directoryPath.c_str())) == NULL)
    {
        std::cout << "Error(" << errno << ") opening " << directoryPath << std::endl;
        return errno;
    }

    while ((dirp = readdir(dp)) != NULL) {
        files.push_back(string(dirp->d_name));
    }
    closedir(dp);
    return 0;
#endif
}
Gilad
  • 6,437
  • 14
  • 61
  • 119
  • What version of C++ are you using? C++14 has experimental support for file systems and it is included in the upcoming C++17 standard. Also there is `boost::filssystem` – NathanOliver Mar 30 '17 at 12:48
  • This is a duplicate of http://stackoverflow.com/questions/612097, which has many creative solutions. – Ulf Lunde Mar 30 '17 at 12:54
  • @NathanOliver gcc 4.8.1 – Gilad Mar 30 '17 at 12:54
  • @UlfLunde I need a file pattern. – Gilad Mar 30 '17 at 12:56
  • Given a list of all files in the directory, you can match them to the pattern yourself. (I'm not saying there is no cross-platform way to fetch a pattern-matched list of files, I have no idea whether there is or not. I'm just saying that you don't *need* that functionality.) – Harry Johnston Mar 31 '17 at 00:24

0 Answers0