opening files from a folder

i need to open files present in a folder. i found a code from here http://www.cplusplus.com/forum/beginner/9173/ to open file. But it gives error that "#include<dirent.h> is undefined". I googled for library and i got here: http://www.softagalleria.net/dirent.php. now from here when i goto download page, page doesn't opens saying "internal server error". My questions are:
1. is it correct method, if yes can someone give me the link to download library?
2. if it is not correct then what is correct method?
dirent.h is a Linux header. If you use Windows, then you need FindFirstFile, FindNextFile, and FindClose to list files in folder as described at https://msdn.microsoft.com/en-us/library/windows/desktop/aa365200(v=vs.85).aspx But if you only need to open a file, you don't need to work with a folder. Just use C++ functions, as described at http://www.cplusplus.com/doc/tutorial/files/ and pass a way to file with directories to open functions.
Last edited on
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <vector>
#include <string>
// #include <ifstream>

#ifdef _MSC_VER // microsoft compiler/library, windows

    #include <experimental/filesystem> // http://en.cppreference.com/w/cpp/experimental/fs
    namespace fs = std::experimental::filesystem ;
    const std::string test_directory = "C:\\windows" ;

#else // #ifdef _GNUG_ // may be GNU compiler, unix or unix-clone

    #include <boost/filesystem.hpp> // http://www.boost.org/doc/libs/1_61_0/libs/filesystem/doc/index.htm
    namespace fs = boost::filesystem ;
    // link with libbost_filesystem libboost_system (-lboost_filesystemn -lboost_system)
    const std::string test_directory = "/usr/local/lib" ;

#endif // microsoft/GNU

std::vector<std::string> get_filenames_in( fs::path path )
{
    std::vector<std::string> filenames ;

    // http://en.cppreference.com/w/cpp/experimental/fs/directory_iterator
    const fs::directory_iterator end{} ;

    for( fs::directory_iterator iter{path} ; iter != end ; ++iter )
    {
        // http://en.cppreference.com/w/cpp/experimental/fs/is_regular_file
        if( fs::is_regular_file(*iter) ) filenames.push_back( iter->path().string() ) ;
    }

    return filenames ;
}

int main()
{
    for( const auto& name : get_filenames_in(test_directory) )
    {
        std::cout << name << '\n' ;

        // std::ifstream file(name) ; // open file for reading
        // ...
    }
}

http://rextester.com/NZUZ1114
http://coliru.stacked-crooked.com/a/fd47754b66de92ae
thanks a lot for help
Topic archived. No new replies allowed.