Iterate Through Files In a Folder/Directory?

Hello --

I know how to read and write to files; however, might there be a way to iterate through the list of files in a folder so that I can pass each one as a variable? If possible, may you list a solution that is not Windows-specific? (I will cross-post this on the UNIX forum).

Thanks!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <vector>
#include <string>
#include <experimental/filesystem> // http://en.cppreference.com/w/cpp/experimental/fs

 
std::vector<std::string> get_filenames( std::experimental::filesystem::path path )
{
    namespace stdfs = std::experimental::filesystem ;

    std::vector<std::string> filenames ;
    
    // http://en.cppreference.com/w/cpp/experimental/fs/directory_iterator
    const stdfs::directory_iterator end{} ;
    
    for( stdfs::directory_iterator iter{path} ; iter != end ; ++iter )
    {
        // http://en.cppreference.com/w/cpp/experimental/fs/is_regular_file 
        if( stdfs::is_regular_file(*iter) ) // comment out if all names (names of directories tc.) are required
            filenames.push_back( iter->path().string() ) ;
    }

    return filenames ;
}

int main()
{
    for( const auto& name : get_filenames( "C:/windows" ) ) std::cout << name << '\n' ;
}

http://rextester.com/PBEMJ47356
Topic archived. No new replies allowed.