如何在更改目录后“更新”diretory_iterator?

时间:2017-07-21 18:13:49

标签: c++ boost boost-filesystem boost-iterators

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

1 个答案:

答案 0 :(得分:0)

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

我的代码中有另一个缺陷,这严重是一个逻辑错误。

解决方案是对几个代码块进行简单的重新排列。

抱歉所有的困惑。