我使用boost::filesystem
遍历所有目录和根目录下的文件(比如说C:\\
)路径。
我已使用recursive_directory_iterator
初始化包含根目录下所有路径的vector<boost::filesystem::path>
路径。
但是有些路径已从目录中删除,我打印的消息说“路径不再存在,路径为......&#34;”。但是我不确定如何获取不再存在的路径名(因为我无法访问该矢量来获取路径名)。
按要求添加代码*
for (size_t i = 0; i < this->paths.size(); i++) {
if (boost::filesystem::exists(this->paths[i])) {
/* get a path from the list of path, ps */
boost::filesystem::path p = this->paths[i];
/* convert path to string */
string path = p.string();
/* check file size(should not be over 10MB) */
if (get_file_size(path) > 10 * pow(10, 6)) continue;
/* setting extension */
string file_extension = boost::filesystem::extension(path);
/* if current path stands for a text file */
if (!file_extension.compare(this->extension)) notify_changes(p);
} else {
cout << "A path no longer exist, the path is.." << endl;
this->paths.erase(this->paths.begin() + i);
}
}
答案 0 :(得分:0)
旧学校循环方法:
<强> Live On Coliru 强>
#include <boost/filesystem.hpp>
#include <iostream>
namespace fs = boost::filesystem;
int main() {
if (system("bash -c 'mkdir -pv tree/{a,b,c}/subdir/; touch tree/{a,b,c}/subdir/{a,b,c}.txt'"))
perror("whoops");
std::vector<fs::path> paths { fs::recursive_directory_iterator { "tree/" }, {} };
if (system("bash -c 'rm -rfv tree/b/subdir/ tree/*/subdir/b.txt'"))
perror("whoops");
for (auto it = paths.begin(); it != paths.end();) {
auto& p = *it;
if (!fs::exists(p))
{
std::cout << "No longer exists: " << p << "\n";
it = paths.erase(it);
continue;
}
// DO PROCESSING
++it;
}
}
<强> Live On Coliru 强>
#include <boost/filesystem.hpp>
#include <boost/range/algorithm.hpp>
#include <iostream>
namespace fs = boost::filesystem;
bool try_to_process(fs::path const& p) // return false if file wasn't found
{
if (!fs::exists(p))
{
std::cout << "No longer exists: " << p << "\n";
return false;
}
// DO PROCESSING
return true;
}
int main() {
if (system("bash -c 'mkdir -pv tree/{a,b,c}/subdir/; touch tree/{a,b,c}/subdir/{a,b,c}.txt'"))
perror("whoops");
std::vector<fs::path> paths { fs::recursive_directory_iterator { "tree/" }, {} };
if (system("bash -c 'rm -rfv tree/b/subdir/ tree/*/subdir/b.txt'"))
perror("whoops");
paths.erase(boost::stable_partition(paths, try_to_process), paths.end());
}
打印
mkdir: created directory `tree'
mkdir: created directory `tree/a'
mkdir: created directory `tree/a/subdir/'
mkdir: created directory `tree/b'
mkdir: created directory `tree/b/subdir/'
mkdir: created directory `tree/c'
mkdir: created directory `tree/c/subdir/'
removed `tree/b/subdir/c.txt'
removed `tree/b/subdir/b.txt'
removed `tree/b/subdir/a.txt'
removed directory: `tree/b/subdir'
removed `tree/a/subdir/b.txt'
removed `tree/c/subdir/b.txt'
No longer exists: "tree/b/subdir"
No longer exists: "tree/b/subdir/c.txt"
No longer exists: "tree/b/subdir/b.txt"
No longer exists: "tree/b/subdir/a.txt"
No longer exists: "tree/a/subdir/b.txt"
No longer exists: "tree/c/subdir/b.txt"