简体   繁体   中英

How can I delete a directory and all files in it with C++?

How can I delete all the files in the directory? I've used rmdir and other methods suggested in the internet but no one helped me: this is one of them: (I want to remove directory tmp in the current work directory)

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

You should look into the Boost Filesystem Library , which provides a number of features that make this sort of thing a lot easier. The example code on the linked page does something very similar to what you want to accomplish (it searches a directory recursively instead of deleting contents recursively).

如果您不想使用Boost,可以执行此操作

rm -r "folder name"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM