【问题标题】:Delete all .txt in a directory with C++使用 C++ 删除目录中的所有 .txt
【发布时间】:2011-08-04 01:49:50
【问题描述】:

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

直到现在,我都在使用这个 -> remove("aa.txt");

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

基本上我想要在 Batch -> del *.txt

中有类似的东西

谢谢!

【问题讨论】:

  • 您使用的是哪个库或框架?
  • 我已经删除了 c 标签,因为你提到了 C++ 两次。

标签: c++


【解决方案1】:
std::string command = "del /Q ";
std::string path = "path\\directory\\*.txt";
system(command.append(path).c_str());

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

我假设您正在运行 Windows。没有标签或 cmets 让我不相信。

【讨论】:

    【解决方案2】:

    您可以使用 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

    br 马辛

    【讨论】:

    • it-&gt;path().extension().compare(".txt") == 0可以写成it-&gt;path().extension() == ".txt"
    【解决方案3】:

    我已经测试过这个解决方案并且它有效。我假设您正在运行 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-13
      • 1970-01-01
      • 2011-02-18
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 2014-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多