在文件名中添加唯一的后缀 [英] Add unique suffix to file name

查看:105
本文介绍了在文件名中添加唯一的后缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Sometimes I need to ensure I'm not overwriting an existing file when saving some data, and I'd like to use a function that appends a suffix similar to how a browser does it - if dir/file.txt exists, it becomes dir/file (1).txt.

推荐答案

这是我制作的使用Qt函数的实现:

This is an implementation I've made, that uses Qt functions:

// 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;
        }
    }
}

这篇关于在文件名中添加唯一的后缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆