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
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With