Skip to content

Instantly share code, notes, and snippets.

@ssendeavour
Created November 5, 2013 19:28
Show Gist options
  • Save ssendeavour/7324701 to your computer and use it in GitHub Desktop.
Save ssendeavour/7324701 to your computer and use it in GitHub Desktop.
Copy file and directories recursively in Qt
//https://qt.gitorious.org/qt-creator/qt-creator/source/1a37da73abb60ad06b7e33983ca51b266be5910e:src/app/main.cpp#L13-189
// taken from utils/fileutils.cpp. We can not use utils here since that depends app_version.h.
static bool copyRecursively(const QString &srcFilePath,
const QString &tgtFilePath)
{
QFileInfo srcFileInfo(srcFilePath);
if (srcFileInfo.isDir()) {
QDir targetDir(tgtFilePath);
targetDir.cdUp();
if (!targetDir.mkdir(QFileInfo(tgtFilePath).fileName()))
return false;
QDir sourceDir(srcFilePath);
QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
foreach (const QString &fileName, fileNames) {
const QString newSrcFilePath
= srcFilePath + QLatin1Char('/') + fileName;
const QString newTgtFilePath
= tgtFilePath + QLatin1Char('/') + fileName;
if (!copyRecursively(newSrcFilePath, newTgtFilePath))
return false;
}
} else {
if (!QFile::copy(srcFilePath, tgtFilePath))
return false;
}
return true;
}
@balmyBanzai
Copy link

You might want to be careful with this snippet. Using cdUp() without checking if your directory is a root directory may cause issues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment