admin管理员组文章数量:1122999
My goal is to determine a filename that is not already taken in a particular folder, in order to save it without erasing any file.
For example, if myname.txt
exists, we should add incremental number like -0000 so it becomes myname-0000.txt
. If both myname.txt
and myname-0000.txt
exist, the filename determined should be myname-0001.txt
and so on.
Also, we want to write the code in a C++/Qt.
My goal is to determine a filename that is not already taken in a particular folder, in order to save it without erasing any file.
For example, if myname.txt
exists, we should add incremental number like -0000 so it becomes myname-0000.txt
. If both myname.txt
and myname-0000.txt
exist, the filename determined should be myname-0001.txt
and so on.
Also, we want to write the code in a C++/Qt.
Share Improve this question asked 22 mins ago Amir HammouteneAmir Hammoutene 768 bronze badges1 Answer
Reset to default 1My solution is this code (please tell me if you think to a better code) :
// returns the path that will not erase any existing file, with added number in filename if necessary
// argument : the initial path the user would like to save the file
QString incrementFilenameIfExists(const QString &path)
{
QFileInfo finfo(path);
if(!finfo.exists())
return path;
auto filename = finfo.fileName();
auto ext = finfo.suffix();
auto name = filename.chopped(ext.size()+1);
auto lastDigits = name.last(4);
if(lastDigits.size() == 4 && lastDigits[0].isDigit() && lastDigits[1].isDigit() && lastDigits[2].isDigit() && lastDigits[3].isDigit() && lastDigits != "9999")
name = name.chopped(4)+(QString::number(lastDigits.toInt()+1).rightJustified(4,'0'));
else
name.append("-0000");
auto newPath = (path.chopped(filename.size()))+name+"."+ext;
return incrementFilenameIfExists(newPath);
}
本文标签: Rename file with incremental number if filename already exists in C QtStack Overflow
版权声明:本文标题:Rename file with incremental number if filename already exists in C++ Qt - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736539278a1944364.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论