Problem, with file type .txt fstream

0

Hello my problem is the following, I use a readdir to read all the files in a directory and it does it perfectly, it reads all its files without problem but the problem lies when I use the ifstream to open and print certain information that there is Inside this, the strange thing is that if you print the files that do not end in .txt as shown in the image. Any idea of how I can correct or why this happens?

#include <iostream> 
#include <dirent.h>
#include <fstream>

using namespace std;

void list_dir(string dir)
{
DIR * directorio;
struct dirent * elemento;
string elem;
if (directorio = opendir(dir.c_str()))
{ 
while (elemento = readdir(directorio))
{
elem = elemento->d_name;
cout<<elem;

ifstream file(elem.c_str());
string a,b,c,d,e,f,g,h,i;
file >>a>>b>>c>>d>>e>>f>>g>>h>>i;
cout<<"Nombre: "<<a<<"  "<<"Celular: "<<c<<"  "<<"Fecha de pago: "<<h<<" "
<<endl;

}            
}
closedir(directorio);
}

void init()
{
cout << "Ruta del directorio a listar: ";
string dir;
getline(cin, dir);
list_dir(dir);   
init();
}

int main(int argc, char *argv[])
{
init();
system("PAUSE");
return 0;
}
    
asked by Andres Franco 24.11.2017 в 02:23
source

1 answer

0

With the option that I have put in the if // marked you will see that the first thing it does is read if they are regular files and the second I have implemented a function so that they end or contain at least the .txt ending, there it goes:

#include <iostream> 
#include <dirent.h>
#include <fstream>

using namespace std;

bool estxt(string s){
   return s.find(".txt");
}

void list_dir(string dir)
{
DIR * directorio;
struct dirent * elemento;
string elem;
if (directorio = opendir(dir.c_str()))
{ 
 while (elemento = readdir(directorio))
 {
  if(elemento->d_type==DT_REG and estxt(elemento->d_name)){//marcado
    elem = elemento->d_name;
    cout<<elem;
    ifstream file(elem.c_str());
    string a,b,c,d,e,f,g,h,i;
    file >>a>>b>>c>>d>>e>>f>>g>>h>>i;
    cout<<"Nombre: "<<a<<"  "<<"Celular: "<<c<<"  "<<"Fecha de pago: "<<h<<" "<<endl;
   }
  }            
 }
closedir(directorio);
}

void init()
{
cout << "Ruta del directorio a listar: ";
string dir;
getline(cin, dir);
list_dir(dir);   
init();
}

int main(int argc, char *argv[])
{
init();
system("PAUSE");
return 0;}
    
answered by 30.11.2017 в 08:51