【问题标题】:How can I delete a directory and all files in it with C++?如何使用 C++ 删除目录及其中的所有文件?
【发布时间】:2011-09-17 19:01:22
【问题描述】:

如何删除目录中的所有文件?我使用了 rmdir 和互联网上建议的其他方法,但没有人帮助我:这是其中之一:(我想删除当前工作目录中的目录 tmp)

removeDir()
{
         char currentPath[_MAX_PATH];
    GetCurrentPath(currentPath);
    std::string tmp(currentPath);

    string path = tmp + "\\temp";


    std::string command = "del  ";
    std::string Path = path + "1.txt"; 
    cout << Path << endl;
    system(command.append(Path).c_str());   
}

GetCurrentPath(char* buffer)
{
    getcwd(buffer, _MAX_PATH);
}   

【问题讨论】:

    标签: c++ file directory


    【解决方案1】:

    【讨论】:

    • @fali boost::filesystem::remove_all("directory");开始将自己与提升世界联系起来。大多数时候,重新发明轮子并不聪明。
    【解决方案2】:

    您应该查看Boost Filesystem Library,它提供了许多使此类事情变得更容易的功能。链接页面上的示例代码所做的事情与您想要完成的非常相似(它递归地搜索目录而不是递归地删除内容)。

    【讨论】:

      【解决方案3】:

      如果您不想使用 Boost,可以这样做

      rm -r "folder name"
      

      【讨论】:

        【解决方案4】:

        http://www.cplusplus.com/reference/clibrary/cstdio/remove/

         int remove ( const char * filename );
        
        #include <stdio.h>
        
        int main ()
        {
          if( remove( "myfile.txt" ) != 0 )
            perror( "Error deleting file" );
          else
            puts( "File successfully deleted" );
          return 0;
        }
        

        【讨论】:

        • OP 和我显然会说一种秘密语言,因为他接受了 :)
        猜你喜欢
        • 2011-08-19
        • 1970-01-01
        • 1970-01-01
        • 2014-03-08
        • 2018-12-27
        • 2020-08-22
        • 2021-12-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多