C++ Qt5 QDir rename returning false

Viewed 367

I am new to Qt and learning about renaming files with the QDir and QFile libraries.

I know how to rename and I can do it but when I try in this loop it does not work.

QDir editFile;
std::cout << "Attempting to chop and put .mp4 onto a regular file.\n";
QString fileNameBuf{argv};
QString fileOriginal{argv};
for(int l{0}; l < fileNameBuf.size(); ++l)
{
    if(fileNameBuf.at(l) == '.')
    {
        fileNameBuf.chop(fileNameBuf.size() - l);
        break;
    }
}
fileNameBuf.append(".mp4");
if(editFile.rename(argv, fileNameBuf))
    std::cout << "Successful\n";
else
    std::cout << "did not make it.\n";

This is actually in a function that sends a QString named argv. argv is a file path. I have it append .mp4 and remove the old extension. I have heard and know that if you do Q rename wrong it will not work. Please help me with this code. I have looked at other posts about this but they do not seem to help.

3 Answers

I hope you are aware that files don't work like that... just changing the extension of a file doesn't mean it result into a new valid file type.

having said that. No need to reinvent the wheel:

check the official doc:

https://doc.qt.io/qt-5/qfile.html#rename-1

QFile editFile{"foo.txt"};
std::cout << "Attempting to chop and put .mp4 onto a regular file.\n";
if(editFile.rename("foo.mp4"))
    std::cout << "Successful\n";
else
    std::cout << "did not make it.\n";

Why use for () for this task if Qt has indexOf () to find a character in the string?

Why not use replace () to change the file extension?

QString::replace does this task easily, because if the string does not contain the source string, it will do nothing...

Like said previously, use Qt's functions. Make sure that if you have this problem that you are not opening the file before renaming it. That was what I was doing wrong here which of corse unless you close it or the file goes out of scope you wont be able to rename it. Thanks for the insights all those who replied.

Related