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

3
我正在尝试使用C++删除一个目录中的所有.txt文件。
到目前为止,我一直在使用这个方法 -> remove("aa.txt");
但现在我需要删除更多的文件,如果我能够只删除所有的.txt文件将会更容易。
基本上,我想要类似于批处理中的这个命令 -> del *.txt
谢谢!

你正在使用哪个库或框架? - laurent
1
我已经删除了c标签,因为您两次提到了C++。 - Greg Hewgill
3个回答

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

静默删除所提供目录中的所有文件。如果未提供 /Q 属性,则会对每个文件进行确认删除。

我假设您正在运行 Windows。没有标签或注释表明其他情况。


这似乎是特定于Windows的。 - undefined

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;
            }
        }
    }
}

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

祝好,Marcin


1
it->path().extension().compare(".txt") == 0 可以写成 it->path().extension() == ".txt" - user102008

0

我已经测试了这个解决方案,它是可行的。我假设你正在运行 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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接