Access several files in a folder with fstream

0

I am carrying out a program which asks me to go through several files that are in a specific folder (they are like 500 files). I have already managed to read a file using fstream , but I would like to see if there is any way to access the folder to access the names and read it one by one.

This is the code I'm using to read a file:

#include<stdlib.h>
#include<string.h>
#include<fstream>
#include<iostream>
using namespace std;

void lectura ();

int main(){
    lectura();
    system("pause");
    return 0;

}

void lectura(){
    ifstream archivo;
    string texto;
    archivo.open("003.html",ios::in); //abre el rachivo

    if(archivo.fail()){
        cout<<" No se pudo abrir el archivo";
        exit(1);
    }

    while(!archivo.eof()){
        getline(archivo,texto);
        cout<<texto<<endl;
    }
    archivo.close();

}
    
asked by Arturo Vera 16.01.2018 в 03:45
source

1 answer

2

If you can compile under the C ++ 17 standard (quite modern standard that will not be available in all the compilers) you can use the filesystem library to inspect the directory in search of the long-awaited list of files. If you can compile under C ++ 14 you may have this library available in experimental :

#include <filesystem>
#include <iostream>
#include <string>

int main()
{
  std::string path = "ruta_del_directorio";
  for (auto & p : std::filesystem::directory_iterator(path))
    std::cout << p << std::endl;
}

If this is not your case and you can use boost , you can try something like this:

#include <iostream>
#include <string>
#include <boost/filesystem.hpp>

int main(int argc, char **argv)
{
  boost::filesystem::path p ("ruta_del_directorio");

  boost::filesystem::directory_iterator end_itr;

  for (boost::filesystem::directory_iterator itr(p); itr != end_itr; ++itr)
  {
    if (boost::filesystem::is_regular_file(itr->path())) {
      std::string current_file = itr->path().string();
      std::cout << current_file << endl;
    }
  }
}

And if none of these possibilities is possible then you have to pull out third-party libraries or customized solutions from your operating system. For example for linux you can use this:

#include <string>
#include <dirent.h>

if( DIR* pDIR = opendir("ruta_del_directorio") )
{
  while(dirent* entry = readdir(pDIR))
  {
    std::string fileName = entry->d_name;

    if( fileName != "." && fileName != ".." )
      std::cout << fileName << '\n';
  }
  closedir(pDIR);
}
    
answered by 16.01.2018 / 07:08
source