Find all the files of a specific extension in a folder in C++
Hello guys, in this tutorial we learn how to find all the files of a specific extension in a folder in C++. For example
for example we have a folder which contain .txt file means files have extension ".txt".files are end_sem.txt mid_term.txt codespeedy.txt Output end_sem mid_term codespeedy
Here we will use the header file dirent.h we use it whenever we want to do directory related work. It helps in the directory traversing.
How to find all the files of a specific extension in a folder in C++
#include<dirent.h> #include<iostream> #include<string> using namespace std; int main() { char *ptr1,*ptr2; // declaring character pointer int y; struct dirent *directory; // creating pointer of type dirent DIR *x; // pointer represent directory stream x = opendir("."); //it will open directory char s[100]; //declaring character array cout<<"enter extension"<<endl; gets(s); // gets fuction will take string as input. if (x!=NULL) { while ((directory = readdir(x)) != NULL) { ptr1=strtok(directory->d_name,"."); ptr2=strtok(NULL,"."); if(ptr2!=NULL) { y=strcmp(ptr2,s); if(y==0) { cout<<ptr1<<endl; } } } closedir(x); } return 0 ; }
opendir- It will open directory stream and take a string as a parameter and return pointer of type DIR if it successfully opens directory or returns a NULL pointer if it is not able to open directory.
closedir- It will close the directory. It will return 0 if it successfully close directory otherwise return 0.
readdir()- It will return pointer of type dirent structure which will represent directory entry at the current position in the directory stream specified by the argument.
strtok- It breaks a string into multiple strings by using a delimiter.
for example pseudo code char s[]=codespeedy.com; char *x=strtok(s,"."); while(x) { cout<<x<<endl; x=strtok(NULL,".") } Output codespeedy com
strcmp-It takes two string as input and compare them lexicographically and returns an integer. If return value 0 it means strings are the same.
Thank you for reading this tutorial on how to find all the files of a specific extension in a folder in C++.
Also read:
Leave a Reply