How to delete files less than specific size in C++
In this article, we will learn how to delete files that are less than a given specific size from a directory in C++.
We will follow the following steps for this –
- Open the directory.
- Iterate through all the files in the directory.
- Get the size of each file while traversing.
- Compare the file size with the given size and if the file size is less than the given size delete it.
Refer to the below code implementation to understand it better-
#include <iostream> #include <dirent.h> #include <sys/stat.h> using namespace std; int main() { DIR *dir; struct dirent *entry; struct stat fileStat; dir = opendir("."); // current directory // To handle the case when directory is null(wrong location is pointed) if (dir == NULL) { cout << "Could not open current directory" << endl; return 1; } // iterating through the directory while ((entry = readdir(dir)) != NULL) { // this will print the file name and it's size cout << entry->d_name << " " << fileStat.st_size << endl; // if file size is less than 10 kb delete it if(fileStat.st_size <10) remove(entry->d_name); } // now close the directory closedir(dir); return 0; }
PS: Be careful while running the program you might lose the important files if the wrong directory is opened.
Leave a Reply