开发者

Save all file names in a directory to a vector

开发者 https://www.devze.com 2022-12-22 02:33 出处:网络
I need to save all \".xml\" file names in a directory to a vector.To make a long story short, I cannot use the dirent API.It s开发者_C百科eems as if C++ does not have any concept of \"directories\".

I need to save all ".xml" file names in a directory to a vector. To make a long story short, I cannot use the dirent API. It s开发者_C百科eems as if C++ does not have any concept of "directories".

Once I have the filenames in a vector, I can iterate through and "fopen" these files.

Is there an easy way to get these filenames at runtime?


Easy way is to use Boost.Filesystem library.

namespace fs = boost::filesystem;
// ...
std::string path_to_xml = CUSTOM_DIR_PATH;
std::vector<string> xml_files;
fs::directory_iterator dir_iter( static_cast<fs::path>(path_to_xml) ), dir_end;
for (; dir_iter != dir_end; ++dir_iter ) {
  if ( boost::iends_with( boost::to_lower_copy( dir_iter->filename() ), ".xml" ) )
    xml_files.push_back( dir_iter->filename() );
}


I suggest having a look at boost::filesystem if it should be portable and bringing boost in isn't too heavy.


If you don't like boost, try Poco. It has a DirectoryIterator. http://pocoproject.org/


Something like this (Note, Format is a sprintf:ish funciton you can replace)

bool MakeFileList(const wchar_t* pDirectory,vector<wstring> *pFileList)
{
    wstring sTemp = Format(L"%s\\*.%s",pDirectory,L"xml");

    _wfinddata_t first_file;

    long hFile = _wfindfirst(sTemp.c_str(),&first_file);

    if(hFile != -1)
    {
        wstring sFile = first_file.name;
        wstring sPath = Format(L"%s%s",pDirectory,sFile.c_str());
        pFileList->push_back(sPath);

        while(_wfindnext(hFile,&first_file) != -1)
        {
            wstring sFile = first_file.name;
            wstring sPath = Format(L"%s%s",pDirectory,sFile.c_str());
            pFileList->push_back(sPath);
        }
        _findclose(hFile);
    }else
        return false;

    return true;    
}
0

精彩评论

暂无评论...
验证码 换一张
取 消