0
我在寫一個使用C++和Boost :: filesystem的程序。該程序應該在給定目錄中拍攝照片並將其移至文件夾。每個文件夾應該只保存給定數量的圖片。如何在更改目錄後「更新」diretory_iterator?
#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++;
}
目前還不清楚你在問什麼。提供[MCVE]。 – Yakk
@Yakk我試圖清理一些。 – Wheathin
現在不太模糊。 「在另一個功能」 - 如果你的意思是「someFunction」說出它的名字。接下來,*簡化*。你的代碼做了很多事情;你可以去掉哪些東西*並仍然會得到相同的症狀*。即,跳過'someFunction'迭代,只需創建*一個*新目錄。問題仍然存在?真棒,案例更簡單。重複,直到你有一個非常簡單的情況。 – Yakk