使用C++删除目录中的所有.txt

Nea*_*eal 2 c++

我正在尝试使用C++删除目录中的所有.txt文件.

到现在为止,我正在使用它 - > remove("aa.txt");

但是现在我有更多要删除的文件,如果我可以删除所有.txt文件会更容易.

基本上我想在Batch - > del*.txt中找到类似的东西

谢谢!

Cas*_*sey 7

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

悄悄删除提供的目录中的所有文件.如果未提供/ Q属性,则它将确认删除每个文件.

我假设你正在运行Windows.没有标签或评论让我相信.


小智 5

您可以使用boost文件系统执行此操作.

#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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此版本区分大小写 - >*it-> path().extension().compare(".txt")== 0.

br Marcin