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

发布于 2024-09-13 00:35:13 字数 1075 浏览 2 评论 0原文

我正在使用 boost::filesystem 重命名文件,如下所示:

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

tmpFileName / targetFile 的类型为 boost::filsystem::path。

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

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

迭代和重命名操作是否可能发生冲突,因为它们都访问目录 inode,或者我还有其他问题吗?

I'm using boost::filesystem to rename a file like this:

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

tmpFileName / targetFile are of type boost::filsystem::path.

While doing this, I iterate over the directory using this code in another thread:

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;
            }
        }
    }

When this code is executed, I get an exception while renaming:

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

Is it possible that the iteration and the rename operation clash, because they both access the directory inode, or do I have some other problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花辞树 2024-09-20 00:35:13

您提供的代码不包含任何文件打开操作,因此无法锁定文件。您迭代目录并重命名文件,对吧?因此该文件可能确实被另一个应用程序(例如文件查看器或其他应用程序)使用,这是非常典型的错误。或者您已在其他地方的应用程序中打开它

code you provided doesn't contain any file open operations, so it cannot lock the file. you iterate over directory and renaming file, right? so it's possible this file is really used by another application like file viewer or something else, it's quite typical error. or you have it opened in your app somewhere else

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文