为文件名添加唯一后缀

时间:2013-08-06 06:46:39

标签: c++ qt filepath

有时我需要确保在保存一些数据时不会覆盖现有文件,并且我想使用一个附加类似于浏览器操作的后缀的函数 - 如果dir/file.txt存在,它变为dir/file (1).txt

3 个答案:

答案 0 :(得分:7)

这是我所做的一个实现,它使用Qt函数:

// Adds a unique suffix to a file name so no existing file has the same file
// name. Can be used to avoid overwriting existing files. Works for both
// files/directories, and both relative/absolute paths. The suffix is in the
// form - "path/to/file.tar.gz", "path/to/file (1).tar.gz",
// "path/to/file (2).tar.gz", etc.
QString addUniqueSuffix(const QString &fileName)
{
    // If the file doesn't exist return the same name.
    if (!QFile::exists(fileName)) {
        return fileName;
    }

    QFileInfo fileInfo(fileName);
    QString ret;

    // Split the file into 2 parts - dot+extension, and everything else. For
    // example, "path/file.tar.gz" becomes "path/file"+".tar.gz", while
    // "path/file" (note lack of extension) becomes "path/file"+"".
    QString secondPart = fileInfo.completeSuffix();
    QString firstPart;
    if (!secondPart.isEmpty()) {
        secondPart = "." + secondPart;
        firstPart = fileName.left(fileName.size() - secondPart.size());
    } else {
        firstPart = fileName;
    }

    // Try with an ever-increasing number suffix, until we've reached a file
    // that does not yet exist.
    for (int ii = 1; ; ii++) {
        // Construct the new file name by adding the unique number between the
        // first and second part.
        ret = QString("%1 (%2)%3").arg(firstPart).arg(ii).arg(secondPart);
        // If no file exists with the new name, return it.
        if (!QFile::exists(ret)) {
            return ret;
        }
    }
}

答案 1 :(得分:3)

QTemporaryFile可以为非临时文件执行此操作,尽管其名称为:

  QTemporaryFile file("./foobarXXXXXX.txt");
  file.open();
  // now the file should have been renamed to something like ./foobarQSlkDJ.txt
  file.setAutoRemove(false);
  // now the file will not be removed when QTemporaryFile is deleted

答案 2 :(得分:0)

更好的解决方案是使用 GUID

或者,您可以根据从文件中收集的字节生成哈希值,可以是随机的,也可以是基于某个文件之间相当独特的数据属性。