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 badges
Add a comment  | 

1 Answer 1

Reset to default 1

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

本文标签: Rename file with incremental number if filename already exists in C QtStack Overflow