gpt4 book ai didi

c++ - 为文件名添加唯一的后缀

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:14:44 24 4
gpt4 key购买 nike

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

最佳答案

这是我使用 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;
}
}
}

关于c++ - 为文件名添加唯一的后缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18073378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com