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 fil开发者_运维百科es.
Basically I want something similar to this in Batch -> del *.txt
Thanks!
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.
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
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;
}
精彩评论