Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to derive a new base file name in Qt?

Tags:

c++

qt

filepath

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
like image 419
sashoalm Avatar asked Nov 14 '12 14:11

sashoalm


2 Answers

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.

like image 72
Tom Panning Avatar answered Oct 31 '22 05:10

Tom Panning


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();
like image 33
coproc Avatar answered Oct 31 '22 06:10

coproc