C ++目录观察 - 如何检测复制已结束 [英] C++ Directory Watching - How to detect copy has ended

查看:138
本文介绍了C ++目录观察 - 如何检测复制已结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件夹复制文件。我想要看它和处理文件,一旦他们被复制到目录。我可以检测文件是否在目录中,无论是通过轮询(我当前的实现)还是在一些测试中使用Windows API从我在线找到的几个示例。

I have a folder to which files are copied. I want to watch it and process files as soon as they are copied to the directory. I can detect when a file is in the directory, whether through polling (my current implementation) or in some tests using Windows APIs from a few samples I've found online.

问题是,我检测到文件第一次创建和仍然被复制。这使我的程序,需要访问该文件,通过错误(因为文件尚未完成)。如何在复制开始但复制结束时检测不到?我在Windows上使用C ++,所以答案可能是依赖于平台,但如果可能,我宁愿它是平台无关。

The problem is that I detect when the file is first created and its still being copied. This makes my program, that needs to access the file, through errors (because the file is not yet complete). How can I detect not when the copying started but when the copying ended? I'm using C++ on Windows, so the answer may be platform dependent but, if possible, I'd prefer it to be platform agnostic.

推荐答案

您可以使用锁定文件或特殊的命名约定。最简单的是后者,并且会工作如下:

You could use either lock files or a special naming convention. The easiest is the latter and would work something like this:

假设你想移动一个名为fileA.txt的文件当把它复制到目的目录时,将它复制到fileA.txt.partial或类似的东西。复制完成后,将文件从fileA.txt.partial重命名为fileA.txt。所以fileA.txt的外观是观察程序可以看到的原子。

Say you want to move a file named "fileA.txt" When copying it to the destination directory, instead, copy it to "fileA.txt.partial" or something like that. When the copy is complete, rename the file from "fileA.txt.partial" to "fileA.txt". So the appearance of "fileA.txt" is atomic as far as the watching program can see.

前面提到的另一个选项是锁定文件。因此,当您复制名为fileA.txt的文件时,您首先创建一个名为fileA.txt.lock的文件。复制完成后,您只需删除锁定文件即可。当观看节目看到fileA.txt时,它应该检查fileA.txt.lock是否存在,如果存在,它可以根据需要等待或重新访问该文件。

The other option as mentioned earlier is lock files. So when you copy a file named "fileA.txt", you first create a file called "fileA.txt.lock". When the copying is done, you simply delete the lock file. When the watching program see "fileA.txt", it should check if "fileA.txt.lock" exists, if it does, it can wait or revisit that file in the future as needed.

这篇关于C ++目录观察 - 如何检测复制已结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆