我已经有一个提升功能,一次删除一个文件夹。 remove_all();
文件夹列表为:
folder1
folder2
folder3
folder4
folder5
我想用上面的函数删除它们,但保留folder2和folder5。
答案 0 :(得分: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;
}