(Dirent.h), List folder txt files

-1

I want to use the dirent.h library to list all the file names of a folder (files type .txt) but that as they are being listed, they are also saved in a string type variable that is also opening it in reading mode with an ifstream. I do not know if you made me understand, the goal is to list some information from .txt files whose names are very big numbers, try it with a for but this progresses quite slow, I attach the for code.

#include <iostream>
#include <fstream>
#include <dirent.h> //aqui la libreria que quiero utilizar.
#include <string>
#include <sstream>

long int x;
string z;

for(x=60400000; x<10000000000; ++x){
string result;
stringstream convert; //Convert de int a string 
convert<<x;//Señalamos la variable a convertir
result=convert.str();//x queda guardada en una variable result con los 
                     //valores de x
z=result+".txt";
/*cout<<z;*///Descomentar para ver el proceso de busqueda.
ifstream file(z.c_str());//Abre la variable z que depende del for.

if (!file){
}

else{
string a,b,c,d,e,f,g,h,i;
file >>a>>b>>c>>d>>e>>f>>g>>h>>i;//Doy un nombre a cada linea del archivo
cout<<"Nombre: "<<a<<"  "<<"Celular: "<<c<<"  "<<"Fecha de pago: "<<h<<" "<<endl;//Imprimo las lineas que necesito especificamente 
    
asked by Andres Franco 23.11.2017 в 23:40
source

1 answer

1

With dirent.h you can get a list of the contents of a directory easily:

DIR *dir;
dirent *ent;
if (DIR* dir = opendir("[ruta directorio]"))
{
  while (dirent* ent = readdir(dir) )
    std::cout << ent->d_name << '\n';
  closedir (dir);
}

Now, in that list you will find that folders are also filtered, including . and .. . If you have a simple mechanism to identify the files ... for example in that folder there are only files or that these are the only ones made up of digits you can use that feature to filter the information you need.

An example (using the C ++ 11 standard) to verify that all characters are numeric digits:

#include <cctype>

while (dirent* ent = readdir(dir) )
{
  std::string nombre = ent->name;
  bool ok = std::all_off(nombre.begin(),nombre.end(),
                         [](char c){ return std::is_digit(c); });
  if( ok )
  {
    std::cout << nombre << '\n';
    // ...
  }
}

If not, you can always use stat.h to inspect the item in question and know if it is a file:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

bool IsFile(std::string const& path)
{
  stat path_stat;
  stat(path.c_str(), &path_stat);
  return S_ISREG(path_stat.st_mode);
}

while (dirent* ent = readdir(dir) )
{
  std::string nombre = ent->name;
  if( IsFile(nombre) )
  if( ok )
  {
    std::cout << nombre << '\n';
    // ...
  }
}
    
answered by 24.11.2017 / 07:39
source