Neal
Neal

Reputation: 286

Delete all .txt in a directory with C++

I'm trying to delete all .txt files in a directory with C++.

Until now, I was using this -> remove("aa.txt");

But now I have more files to delete and would be easier if I could just delete all the .txt files.

Basically I want something similar to this in Batch -> del *.txt

Thanks!

Upvotes: 3

Views: 11136

Answers (3)

ashuvssut
ashuvssut

Reputation: 2275

I have tested this solution and it works. I assume you're running windows.

#include <stdlib.h>
#include <string.h>
// #include <iostream>

using namespace std;
int main() {
    char extension[10] = "txt", cmd[100] = "rm path\\to\\directory\\*.";

    // cout << "ENTER EXTENSION OF FILES : \n";
    // cin >> extension;
    strcat(cmd, extension);
    system(cmd);
    return 0;
}

Upvotes: 0

Marcin Marek
Marcin Marek

Reputation: 153

You can do this with boost filesystem.

#include <boost/filesystem.hpp> 
namespace fs = boost::filesystem;

int _tmain(int argc, _TCHAR* argv[])
{
    fs::path p("path\\directory");
    if(fs::exists(p) && fs::is_directory(p))
    {
        fs::directory_iterator end;
        for(fs::directory_iterator it(p); it != end; ++it)
        {
            try
            {
                if(fs::is_regular_file(it->status()) && (it->path().extension().compare(".txt") == 0))
                {
                    fs::remove(it->path());
                }
            }
            catch(const std::exception &ex)
            {
                ex;
            }
        }
    }
}

This version is case sensitive -> *it->path().extension().compare(".txt") == 0.

br Marcin

Upvotes: 6

Casey
Casey

Reputation: 10936

std::string command = "del /Q ";
std::string path = "path\\directory\\*.txt";
system(command.append(path).c_str());

Quietly deletes all files in the supplied directory. If the /Q attribute is not supplied then it will confirm delete for every file.

I assume you're running windows. No tags or comments lead me to believe otherwise.

Upvotes: 8

Related Questions