Access to the file system is platform dependent, so without knowing the operating system you work with, you only have to use a generic library like Boost Filesystem , in its tutorial have an example of how to navigate the elements of a folder:
Boost
#include <boost/filesystem.hpp>
void muestra_contenido_de(const std::string &a_carpeta)
{
boost::filesystem::path p(a_carpeta);
if (boost::filesystem::exists(p) && boost::filesystem::is_directory(p))
{
std::cout << p << " contiene:\n";
for (auto &x : boost::filesystem::directory_iterator(p))
cout << " " << x.path() << '\n';
}
}
If you can not or do not want to use Boost, your code should be platform dependent, in Windows:
Windows
#include <windows.h>
void muestra_contenido_de(const std::string &a_carpeta)
{
WIN32_FIND_DATA ffd{};
if (auto handle = FindFirstFile((a_carpeta + "/*.*").c_str(), &ffd))
{
do
{
std::cout << ffd.cFileName << '\n';
}
while (FindNextFile(handle, &ffd) != 0);
}
}
And here for Linux:
Linux
#include <dirent.h>
void muestra_contenido_de(const std::string &a_carpeta)
{
if (DIR *dpdf = opendir(a_carpeta.c_str()))
{
dirent *epdf = nullptr;
while (epdf = readdir(dpdf))
{
std::cout << epdf->d_name << '\n';
}
}
}
As a final note, the approval of the C ++ 17 standard is foreseen for this August, this standard is expected to include a standard file system access library, you can read the technical documents of this proposal here:
-
P0218R0
Adopt the file system technical specification for C ++ 17.
-
P0219R1
Relative Routes for File System (First revision).
-
P0317R1
Cache for directory_entry
(First revision).
-
P0392R0
Filesystem paths must adapt string_view
.
-
P0430R2
File system library on non-POSIX operating systems.
-
P0492R2
Proposed resolutions to the comments of C ++ 17 National Body on File System (Second revision).
This new standard library will allow the following:
C++17
#include <filesystem>
void muestra_contenido_de(const std::string &a_carpeta)
{
for (auto &p : std::filesystem::directory_iterator(a_carpeta))
std::cout << p << '\n';
}