gpt4 book ai didi

c++ - directory_iterator file_iter 重命名文件夹中的文件

转载 作者:行者123 更新时间:2023-11-28 03:34:51 26 4
gpt4 key购买 nike

我想重命名目录中的文件。目录中有 52 个文件夹。每个文件夹都有不同的名称,每个文件夹中有大约 40 个文件。我想提取特定文件夹的名称并将该名称附加到该特定文件夹中的文件名称。 当每个文件夹中只有 31 个或更少的文件时,它工作正常。但是只要特定文件夹中的文件数超过 31,我编写的重命名算法就会失败。我无法弄清楚为什么当有更多文件时它会崩溃。如果你明白为什么……请赐教!我附上代码:

int main( int argc, char** argv ){
directory_iterator end_iter;
directory_iterator file_itr;

string inputName;
string checkName;
inputName.assign(argv[1]);


if (is_directory(inputName))
{

for (directory_iterator dir_itr(inputName); dir_itr != end_iter; ++dir_itr)
{
if (is_directory(*dir_itr))
{
for (directory_iterator file_itr(*dir_itr); file_itr != end_iter; ++file_itr)
{
string folderName(dir_itr->path().filename().string());
if (is_regular_file(*file_itr))
{
std::string fileType = file_itr->path().extension().string();
std::transform(fileType.begin(), fileType.end(), fileType.begin(), (int(*)(int))std::toupper);
if (fileType == ".JPG" || fileType == ".JPEG" || fileType == ".JPG" || fileType == ".PGM")
{
string filename(file_itr->path().string());
string pathName(file_itr->path().parent_path().string());
string oldName(file_itr->path().filename().string());

cout << folderName << endl;
folderName += "_";
folderName += oldName;

string newPathName = pathName + "\\" + folderName;
cout << pathName <<"\\"<< folderName << endl;

//RENAMING function
rename(file_itr->path(), path(newPathName.c_str()));

}
}
}
}
}

}

最佳答案

很可能是 Boost 的 directory_iterator重命名目录列表中的文件会使实现变得困惑。

来自文档:

Warning: If a file or sub-directory is removed from or added to a directory after the construction of a directory_iterator for the directory, it is unspecified whether or not subsequent incrementing of the iterator will ever result in an iterator whose value is the removed or added directory entry.

我建议分两个阶段尝试。在第一阶段,使用您现在拥有的代码构建一个 vector<pair<string, string> >而不是重命名文件。然后,一旦您扫描了目录,只需遍历执行实际重命名的列表即可。

关于c++ - directory_iterator file_iter 重命名文件夹中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11261939/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com