我正在使用 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++;
}