tags:

views:

77

answers:

4

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 seems 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?

+5  A: 

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() );
}
Kirill V. Lyadvinsky
+3  A: 

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

pmr
+2  A: 

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

Budric
+1  A: 

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;    
}
RA
_wfindfirst doesn't look like part of C++ Standard.
Kirill V. Lyadvinsky
Took a wild guess that it was Windows
RA