Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QT copy to QTemporaryFile

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?

like image 815
Eric Avatar asked Jul 29 '14 12:07

Eric


2 Answers

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.

like image 109
RobbieE Avatar answered Oct 16 '22 09:10

RobbieE


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?

like image 21
Kuba hasn't forgotten Monica Avatar answered Oct 16 '22 11:10

Kuba hasn't forgotten Monica