代码之家  ›  专栏  ›  技术社区  ›  VolkA

Windows:文件重命名和目录迭代冲突

  •  0
  • VolkA  · 技术社区  · 15 年前

    boost::filesystem::rename(tmpFileName, targetFile);
    

    在执行此操作时,我在另一个线程中使用以下代码遍历目录:

    directory_iterator end_itr;
    for (directory_iterator itr(dirInfoPath); itr != end_itr; ++itr)
    {
        path currentPath = itr->path();
        if (is_directory(itr->status()))
        {
            // skip directories
        }
        else 
        {
            std::string file_name = currentPath.leaf();
            if (!boost::algorithm::starts_with(file_name, "new") 
                && !boost::algorithm::starts_with(file_name, "finished")
                && boost::algorithm::ends_with(file_name, ".info"))
                {
                    // save found filename in some variable
                    return true;
                }
            }
        }
    

    执行此代码时,重命名时出现异常:

    boost::filesystem::rename: The process cannot access the file because it is being used by another process
    

    1 回复  |  直到 15 年前
        1
  •  1
  •   Andriy Tylychko    15 年前

    您提供的代码不包含任何文件打开操作,因此不能 lock 文件。你重复了一遍 directory 和重命名 file ,对吧?所以这个文件可能真的被 像文件查看器之类的应用程序,这是非常典型的错误。或者你在其他地方的应用程序中打开了它