How to delete empty files from a directory in C++

Here in this tutorial, we are going to learn how to delete empty files from a directory in C++. The <filesystem> library in C++ 17 provides a very powerful method to iterate over directories. It provides various classes to manage files. We will also be using another C++ library <fstream> to read files. <fstream> is basically the combination of both <ofstream> and <ifstream>. It provides the capability of creating, writing and reading a file. To access the following classes, you must include the <fstream> as a header file like how we declare <iostream> in the header.

Delete empty files from a directory in C++

Let us start our tutorial on how to delete files from a directory in C++.

You may also check out: Tutorial: File Handling in C++

 

First of all, we are going to add <fstream> and <filesystem> in the preprocessor directives. <filesystem> has been added in C++17 to make file handling easy. We are using std(standard) namespace and we have used fs in place of filesystem just to ease the writing of code, you can simply write filesystem in place of fs. To have a better understanding of namespace do visit:-

#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
namespace fs = filesystem;

 

Next, in our main function, we are going to take the directory to iterate as input. We are going to create an iterator named “entry” to iterate over the directory to search for empty files. We have also used is_empty(), which returns a boolean value of true if the file is empty and returns false if it is not empty.

int main(){
string path;
 cout<<"Enter the path to directory: "<<endl;
 cin>>path;
 for (const auto &entry : fs ::directory_iterator(path)) {
   string s = entry.path();
   ifstream file(s);

   if (fs::is_empty(s)) {
     fs::remove(s);
   }
 }
 cout << "files deleted";
}

Ifstream in C++ is a file input stream that allows us to read any information contained in the file. We need to include the <iostream> and <stream> header files in our code to use these stream classes. The remove() function helps you delete the file and takes a string i.e (name of the file) as a parameter.

 

Here is the full code:-

#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>

using namespace std;
namespace fs = filesystem;

int main() {
  
  string path;
  cout<<"Enter the path to directory: "<<endl;
  cin>>path;
  for (const auto &entry : fs ::directory_iterator(path)) {
    string s = entry.path();
    ifstream file(s);

    if (fs::is_empty(s)) {
      fs::remove(s);
    }
  }
  cout << "files deleted";
}

Output:

Delete empty files from a directory in C++

How to delete empty files from a directory in C++

 

Empty files get deleted!

Leave a Reply

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