Distinguish folders and files in C ++

I have this code that opens a directory and checks to see if this list is a regular file (meaning it is a folder), it will open it as well. How can I distinguish files and folders with C ++. here is my code if this helps:

#include <sys/stat.h> #include <cstdlib> #include <iostream> #include <dirent.h> using namespace std; int main(int argc, char** argv) { // Pointer to a directory DIR *pdir = NULL; pdir = opendir("."); struct dirent *pent = NULL; if(pdir == NULL){ cout<<" pdir wasn't initialized properly!"; exit(8); } while (pent = readdir(pdir)){ // While there is still something to read if(pent == NULL){ cout<<" pdir wasn't initialized properly!"; exit(8); } cout<< pent->d_name << endl; } return 0; 

}

+6
source share
2 answers

One of the methods:

 switch (pent->d_type) { case DT_REG: // Regular file break; case DT_DIR: // Directory break; default: // Unhandled by this example } 

You can find the struct dirent documentation in the GNU C Library Manual .

+7
source

For completeness, another way:

  struct stat pent_stat; if (stat(pent->d_name, &pent_stat)) { perror(argv[0]); exit(8); } const char *type = "special"; if (pent_stat.st_mode & _S_IFREG) type = "regular"; if (pent_stat.st_mode & _S_IFDIR) type = "a directory"; cout << pent->d_name << " is " << type << endl; 

You will need to correct the file name with the source directory if it is different from .

+1
source

Source: https://habr.com/ru/post/908555/


All Articles