PDA

View Full Version : File timestamp transfer on windows in QT when copying files



rucs_hack
28th April 2011, 12:20
Since QT doesn't nativelly copy over file information when it does a file copy (specifically creation, last modified and last accessed times), and I needed this, I've written a function that does this using a combination of QT and the Windows API.

I thought someone else might find it useful, because I found a fair few posts on the net with people asking to do this very thing. It's not cross platform, obviously.
I may add #ifdef stuff and put in linux attribute copying as well later, when I need it.



#include <QObject>
#include <windows.h>
#include <qfile.h>
#include <qtextstream.h>
#include <iostream>
#include <qdir>
#include <QString>
// file copy operation that preserves file timestamps
bool copyFile(QString srcFile,QString dstFile) {
QFile sourceFile(srcFile);
FILETIME ftCreate, ftAccess, ftWrite;
if (!sourceFile.open(QIODevice::ReadOnly))
return false;
QFile destFile(dstFile);
if (!destFile.open(QIODevice::WriteOnly))
return false;
destFile.write(sourceFile.readAll());
sourceFile.close();
destFile.close();
wchar_t *srcPath = new wchar_t[srcFile.length()];
for (int i(0);i<srcFile.length();i++) {
srcPath[i] = srcFile.toStdString().c_str()[i];
}
wchar_t *dstPath = new wchar_t[dstFile.length()];
for (int x(0);x<dstFile.length();x++) {
dstPath[x] = dstFile.toStdString().c_str()[x];
}
HANDLE sfile = CreateFile(srcPath,0,0,NULL,OPEN_ALWAYS,FILE_ATTRI BUTE_READONLY,NULL);
HANDLE dfile = CreateFile(dstPath,GENERIC_WRITE,0,NULL,OPEN_EXIST ING,FILE_ATTRIBUTE_NORMAL,NULL);
GetFileTime(sfile,&ftCreate, &ftAccess, &ftWrite);
SetFileTime(dfile,&ftCreate, &ftAccess, &ftWrite);
CloseHandle(sfile);
CloseHandle(dfile);
delete [] srcPath;
delete [] dstPath;
return true;
}


I've taken this out of a larger class that does a lot more file and directory operations, so some of the includes here might not be needed. This code is also on my blog, but since I'm still a relativelly new poster here I thought links to personal sites might not be allowed.

squidge
28th April 2011, 13:16
Since you are being Windows specific, you could also just use CopyFile(from,to) function which also copies file attributes (eg. read only).

If you want to copy security attributes also, you can use SHFileOperation with wFunc set to FO_COPY