c++ linux/windows 文件夾下指定後綴文件列表讀取(不依賴任何第三方庫,如boost、opencv、qt等)

#ifdef _WIN32
void GetFiles(const std::string &path, std::vector<std::string>& files)
{
	// file handle
	long hFile = 0;
	//file info
    struct _finddata_t fileinfo;
	std::string p;
	if ((hFile = _findfirst(p.assign(path).append("/*.jpg").c_str(), &fileinfo)) != -1)
	{
		do
		{
			//if a directory, recursive
			//else push into the vector  
			if ((fileinfo.attrib &  _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
				{
					GetFiles(p.assign(path).append("/").append(fileinfo.name), files);
				}

			}
			else
			{
				files.push_back(p.assign((fileinfo.name)));
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}
}
#else
void GetFiles(const std::string &path, std::vector<std::string>& files)
{
    const std::string& exten = ".jpg";
    files.clear();

    DIR* dp = nullptr;
    struct dirent* dirp = nullptr;
    if ((dp = opendir(path.c_str())) == nullptr)
    {
        return;
    }

    while ((dirp = readdir(dp)) != nullptr)
    {
        if (dirp->d_type == DT_REG)
        {
            if (exten.compare("*") == 0)
            {
                files.emplace_back(static_cast<std::string>(dirp->d_name));
            }
            else
            {
                if (std::string(dirp->d_name).find(exten) != std::string::npos)
                {
                    files.emplace_back(static_cast<std::string>(dirp->d_name));
                }
            }
        }
    }

    closedir(dp);
}
#endif
發佈了27 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章