From f9dd32c6e356d8a3717b391b667b6cf2b3419baa Mon Sep 17 00:00:00 2001 From: LoRd_MuldeR Date: Wed, 14 Dec 2016 15:04:23 +0100 Subject: [PATCH] Added function to generate unique file name, using an increasing counter. --- include/MUtils/Global.h | 3 ++- src/Global.cpp | 30 ++++++++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/include/MUtils/Global.h b/include/MUtils/Global.h index 3bd3a5a..8807d32 100644 --- a/include/MUtils/Global.h +++ b/include/MUtils/Global.h @@ -84,8 +84,9 @@ namespace MUtils MUTILS_API quint32 next_rand32(void); MUTILS_API quint64 next_rand64(void); - //Temp File Name + //File Name MUTILS_API QString make_temp_file(const QString &basePath, const QString &extension, const bool placeholder = false); + MUTILS_API QString make_unique_file(const QString &basePath, const QString &baseName, const QString &extension, const bool fancy = false); //Parity MUTILS_API bool parity(quint32 value); diff --git a/src/Global.cpp b/src/Global.cpp index 0c6260a..a9a9f4e 100644 --- a/src/Global.cpp +++ b/src/Global.cpp @@ -112,7 +112,7 @@ QString MUtils::rand_str(const bool &bLong) } /////////////////////////////////////////////////////////////////////////////// -// GET TEMP FILE NAME +// GENERATE FILE NAME /////////////////////////////////////////////////////////////////////////////// QString MUtils::make_temp_file(const QString &basePath, const QString &extension, const bool placeholder) @@ -138,10 +138,36 @@ QString MUtils::make_temp_file(const QString &basePath, const QString &extension } } - qWarning("Failed to generate unique temp file name!"); + qWarning("Failed to generate temp file name!"); return QString(); } +QString MUtils::make_unique_file(const QString &basePath, const QString &baseName, const QString &extension, const bool fancy) +{ + quint32 n = fancy ? 2 : 0; + QString fileName = fancy ? QString("%1/%2.%3").arg(basePath, baseName, extension) : QString(); + while (fileName.isEmpty() || QFileInfo(fileName).exists()) + { + if (n <= quint32(USHRT_MAX)) + { + if (fancy) + { + fileName = QString("%1/%2 (%3).%4").arg(basePath, baseName, QString::number(n++), extension); + } + else + { + fileName = QString("%1/%2.%3.%4").arg(basePath, baseName, QString::number(n++, 16).rightJustified(4, QLatin1Char('0')), extension); + } + } + else + { + qWarning("Failed to generate unique file name!"); + return QString(); + } + } + return fileName; +} + /////////////////////////////////////////////////////////////////////////////// // COMPUTE PARITY /////////////////////////////////////////////////////////////////////////////// -- 2.11.4.GIT