Find a specific file in a directory in C++

Hello, guys in this tutorial we will learn about how to find a specific file in a directory inĀ  C++. We will look at some examples then we move further.

Directory- C:\\Users\\MyPC\\Desktop\\codespeedy has file 
codespeedy.exe
helloworld.cpp
factorial.cpp
Input
helloworld.cpp
Output
file present in directory
Input
array_sum
Output
file is not present in directory

C++ program to find a specific file in a directory

#include<iostream>
#include<dirent.h>
using namespace std;
int main() 
{

DIR *directory;   // creating pointer of type dirent

struct dirent *x;   // pointer represent directory stream

cout<<"Please enter file name with its extension"<<endl;  

string s;  //declaring string variable

cin>>s;  // taking string as input or file name with input

bool  result=false;  //declaring string variable and assign it to false.

if (( directory= opendir ("C:\\Users\\MyPC\\Desktop\\codespeedy")) != NULL) {      // check if directory  open
  
  while ((x = readdir (directory)) != NULL) {
  	
  	{
  		
  		if(s==x->d_name)
  		{
  			result=true;  //if file found then  assign  result to false.
  			
  	        break;     // break the loop if file found.
  			
      }
  		
  		
  }
  	
   
  }
 
  
  closedir (directory); //close directory....
  
  
  
}

 if(result)   // if file is present then....
  {
  	cout<<"file is present"<<endl; 	
  }
  else    //if file is not present....
  {
  	cout<<"file is not present"<<endl;
  } 
  



}

 

Explanation of the above program:

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.

Note-If you are running above code on your machine please change directory address according to your need.

Thank you for reading this tutorial on how to find a specific file in a directory in C++.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *