sashoalm
sashoalm

Reputation: 79467

How to derive a new base file name in Qt?

What is the best/most standard way to rename just the base file name of a given file path in Qt, while preserving the directory and extension?

Is there a standard way to do that, or do I just use regular expressions?

Let's say I have:

/home/user/myfile.png

And it would be changed to:

/home/user/myfile-modified.png

Upvotes: 5

Views: 4290

Answers (2)

Tom Panning
Tom Panning

Reputation: 4772

Use QFileInfo to parse out the aspects of the path.

QFileInfo original("/home/user/myfile.png");
QString newPath = original.canonicalPath() + QDir::separator() + original.baseName() + "-modified";
if (!original.completeSuffix().isEmpty())
    newPath += "." + original.completeSuffix();

Warning: If your filename ends with a '.', but doesn't have an extension, this will drop the '.'. In other words, /home/user/myfile. will be renamed to /home/user/myfile-modified. Otherwise, this should work.

Upvotes: 6

coproc
coproc

Reputation: 6247

not tested, but this might work:

const char* filePath = "/home/user/myfile.png";
QFileInfo file(filePath);
QDir dir = file.dir();
QString baseName = file.baseName();
QString baseNameModified = ...; // insert here your logic for modifying filename
QFileInfo fileModified(dir, baseNameModified);
QString filePathModified = fileModified.filePath();

Upvotes: 1

Related Questions