对目录进行更改后,如何"update" diretory_iterator?

How do you "update" a diretory_iterator after changes to a directory have been made?

本文关键字:update 如何 diretory iterator      更新时间:2023-10-16

我正在使用C++和Boost::filesystem编写一个程序。该程序应该在给定目录中拍照并将它们移动到文件夹中。每个文件夹应该只容纳给定数量的图片。

#include<string>
#include<boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
vector<path> new_folders; //vector of paths that will be used to copy things
//I know a global variable is a bad idea, but this is just a simplified example of my program    
void someFunction(path somePath)
{
directory_iterator iter(somePath);
directory_iterator end_iter;
int count = 0;//used in the naming of folders
while(iter != end_iter)
{
string parentDirectory = iter->path().string(); 
string newFolder = "\Folder " + to_string(count+1);
parentDirectory.append(newFolder);
path newDir = parentDirectory;
create_directory(newDir);//create new folder in parent folder
new_folders.push_back(newDir); //add path to vector
count++;
iter++;
}
}

void fill_folders(path pic_move_from, const int MAXIMUM)
{
//this iterator does not account for the new folders that were made      
//-------------------- HERE IS WHERE the problem is located
directory_iterator iterate(pic_move_from);
directory_iterator end_iter;
//fill the new folders with pictures
for (int folderNum = 0; folderNum < new_folders.size(); folderNum++)
{
path newFolder = new_folders.at(folderNum);
int loopCount = 0; //for the following while loop
while (loopCount != MAXIMUM && iterate != end_iter)
{
if(is_regular_file(*iterate) && img_check(iterate))//item must be a picture to be copied
{ 
create_copy_multifolder(iterate, newFolder);
}//end if
iterate++;
//the loopCount in the while loop condition should be the max number of folders
loopCount++;
}//end while loop
}//end for loop
}//end fill_folders function

int main()
{
path myPath = "C:\Users\foo";
const int MAX = 2; //maximum number of pictures per folder
someFunction(myPath);
fill_folders(myPath, MAX); 
return 0;
}

路径pic_move_from用于另一个函数。这个其他函数为此path使用了一个目录迭代器,并在相同的函数中将目录添加到path pic_move_from引用的目录中。我尝试为此目录创建一个新的迭代器,以便我可以将目录中的任何图片移动到新添加的子目录中。但是,新directory_iterator不会"更新"以处理目录中的新条目。那么,如何"更新"directory_iterator呢?

更新:我试图尽可能地简化这段代码,所以我想出了下面的测试/示例。此示例工作正常,并在第二次迭代期间打印出新文件夹,因此我必须仔细检查原始代码中的所有内容。

string pathToFile = "C:\foo";
path myPath();
directory_iterator iter(pathToFile);
directory_iterator end_iter;
while (iter != end_iter)
{
cout << endl << iter->path().filename().string() << endl;
iter++;
}
string pathToNew = pathToFile;
pathToNew.append("\Newfolderrrrr");
create_directory(pathToNew);
directory_iterator iterate(pathToFile);
directory_iterator end_iterate;
while (iterate != end_iterate)
{
cout << endl << iterate->path().filename().string() << endl;
iterate++;
}

事实证明,目录迭代器或我如何使用它们没有问题。

我的代码中还有另一个缺陷,严格来说是一个逻辑错误。

解决方案是简单地重新排列几个代码块。

很抱歉所有的困惑。