79346841

Date: 2025-01-10 19:43:53
Score: 1.5
Natty:
Report link

My 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);
}
Reasons:
  • Whitelisted phrase (-1): solution is
  • RegEx Blacklisted phrase (2.5): please tell me
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: Amir Hammoutene