2012-12-31 276 views
2

我已经有一个提升功能来一次删除一个文件夹。 remove_all();删除除特定文件夹以外的所有文件夹

文件夹列表是:

folder1 
folder2 
folder3 
folder4 
folder5 

我想删除所有与我上面的功能,但保持文件夹2和folder5。

+2

你不能遍历文件夹和检查,如果他们不'folder2'或'folder5',如果不删除它们? – Cornstalks

+0

加载你想*保存*到std :: set ,然后将其传递给增强删除功能,该功能仅删除该组中的项目* not *。如果您要递归到子文件夹中,您可能必须具有创意。 – WhozCraig

+0

编写一个函数,其中包含“要保留的文件夹”列表,并将每个“可能删除此文件”与“要保留的文件夹”列表进行比较,如果它位于保留列表中,请不要删除它(或写入“ha哈,删除它反正“删除后,你的狡猾!) –

回答

1

我已经找到了2种方法如何做到这一点。

首先我把我的文件夹列表放到一个数组中。

第一种方式:使用函数来查找我的字符串数组中的子字符串,然后将其删除。

第二种方式:使用strcmp与我的字符串数组进行比较,然后删除找到的搜索标签。

这里是最终代码:

// simple_ls program form boost examples 
// http://www.boost.org/doc/libs/1_52_0/libs/filesystem/example/simple_ls.cpp 
#define BOOST_FILESYSTEM_VERSION 3 

// We don't want to use any deprecated features 
#ifndef BOOST_FILESYSTEM_NO_DEPRECATED 
# define BOOST_FILESYSTEM_NO_DEPRECATED 
#endif 
#ifndef BOOST_SYSTEM_NO_DEPRECATED 
# define BOOST_SYSTEM_NO_DEPRECATED 
#endif 

#include "boost/filesystem/operations.hpp" 
#include "boost/filesystem/path.hpp" 
#include "boost/progress.hpp" 
#include <iostream> 
#include <cstring> 

using namespace std; 
using namespace boost::filesystem; 
unsigned long dir_count = 0; 

void RemoveSub(string& sInput, const string& sub) { 
    string::size_type foundpos = sInput.find(sub); 
    if (foundpos != string::npos) 
     sInput.erase(sInput.begin() + foundpos, sInput.begin() + foundpos + sub.length()); 
} 

int listDir(string d) { 
d.erase(
remove(d.begin(), d.end(), '\"'), 
d.end() 
); //Remove Quotes 

if (!is_directory(d)) { 
    cout << "\nNot found: " << d << endl; 
    return 1; 
    } 
    directory_iterator end_iter; 
    for (directory_iterator dir_itr(d); 
     dir_itr != end_iter; 
     ++dir_itr) { 
      if (is_directory(dir_itr->status())) { 
      ++dir_count; 
      string v = dir_itr->path().filename().string(); 
      v.erase(
      remove(v.begin(), v.end(), '\"'), 
      v.end() 
      ); 
      string m[] = { v }; 
      string mm = m[0].c_str(); 
      RemoveSub(mm, "folder2"); // Keep folder2 
      RemoveSub(mm, "folder5"); // Keep folder5 
/* 
      if(strcmp(m[0].c_str(), "folder2") == 0) mm.erase (mm.begin(), mm.end()); // Keep folder2 
      if(strcmp(m[0].c_str(), "folder5") == 0) mm.erase (mm.begin(), mm.end()); // Keep folder5 
*/ 
      if(!mm.empty()) { // Remove folders 
      cout << "\nRemoving: " << mm << " ..."; 
      remove_all(d+"/"+mm); 
      } 
     } 
    } 
    return 0; 
} 

int main(int argc, char* argv[]) { 
string i; 
cout << "\nx: Exit\n\nDelete all folders in: "; 
getline(cin,i); 
if(i=="X" || i=="x") return 0; 
if(i.empty()) return 0; 

listDir(i); //Call our function 
return 0; 
} 
+0

此解决方案对字符串操作的严重依赖性使得(1)难以阅读并且(2)容易出错。您应该尝试合并@WhozCraig提示的使用集合来存储您想要保存的目录,并更多地使用boost :: filesystem为您提供的类型和函数,而不是用完整路径的字符串表示来摆弄。 – us2012

相关问题