I'd like to make a copy of some/path/myfile
in $TMPDIR/myprog-<random-string>.ext
, such that I can then pass it on to a 3rd party procedure that chokes on extensionless files.
Here's what I'd like to work:
QString originalPath = "some/path/myfile";
QTemporaryFile f(
QDir::temp().absoluteFilePath("mprog-XXXXXX.ext")
);
// f.open(); ?
QFile(originalPath).copy(f.fileName());
However, I now have a problem - either the file doesn't yet exist, and thus hasn't been assigned a temporary fileName()
, or the file name has been assigned but the file itself already exists, preventing the new file being copied on top.
How can I copy a file to a temporary location in QT, and have the temporary copy removed when the destructor of QTemporaryFile is called?
If the file doesn't exist, create the QTemporaryFile
object exactly as you have done, open it and then close it immediately. This will generate the random filename and create it on the disk.
When your QTemporaryFile
object gets destroyed, the file will be deleted from the disk.
Unfortunately, Qt (5.3) doesn't support copying to an existing file. The only correct, race-free use of QTemporaryFile
is to open()
it, creating it in the process, and then operate on it.
You'll need to implement the copy yourself, I'm afraid :(
On Windows, if you expect there to be some gain from using CopyFileEx
, I have a complete example that wraps it for Qt's perusal, with progress signals.
The real question is: do you really need to create a copy? Wouldn't a hard link do? Since Qt runs, for the most part, on Unices and Windows, you can create a symbolic link wrapper that will wrap POSIX link()
and winapi CreateHardLink
. If hard link creation fails, or the temporary folder is on a different volume, you can then try CreateSymbolicLink
. Of course you'd need to look up CreateSymbolicLinkW
using QLibrary
if you intend your executable to start un XP at all. If that fails, you're either running on XP or on a FAT partition, and the final fallback is copying.
Would it be out of the question to rename the file, run the 3rd-party application on it, then rename it back?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With