Valentin H
Valentin H

Reputation: 7448

Can't remove file previously created by the application in Qt 4.8 on Win 7

I've copied a .bat-file from Qt-ressources to a file system and executed it. After that I wanted to delete the file, but it fails in Qt. If fails also when I restart the application. However, the file can be removed in the file-explorer.

I tried QFile::remove as well as QDir::remove. Static as well as not-static versions - no effect. I tried to call using native file-separator - didn't help either.

What is wrong with this code?

if ( QFileInfo( dataRootPath+"/backupdb.bat" ).exists() )
{
    //debugger stepps in
    QFile f( QFileInfo( dataRootPath+"/backupdb.bat" ).canonicalFilePath());
    f.remove(  );
}

Upvotes: 0

Views: 1990

Answers (3)

Raven
Raven

Reputation: 3526

I encountered the same error, but in my case the posted solutions did not work. However, it turned out that I had created a std::ofstream object in my code, that was unclosed. Thus, this was keeping the source file open which prevented the copying on Windows.

Upvotes: 1

vabawen
vabawen

Reputation: 11

I change its permissions before remove it.

QFile::copy(":/res/1.txt", "D:\\1.txt");
QFile file("D:\\1.txt");
file.setPermissions(file.permissions() |
                    QFileDevice::WriteOwner |
                    QFileDevice::WriteUser |
                    QFileDevice::WriteGroup |
                    QFileDevice::WriteOther);
file.remove();

Upvotes: 1

Filipp  Slavnejshev
Filipp Slavnejshev

Reputation: 128

I had the same problem copying file from resources to file system and trying to remove it after that. QFile::errorString() returns "Access denied". So it seems that resource file has some nasty permissions that are copied by QFile::copy. May be it's possible to change permissions but I used my own 2 functions to copy file:

bool copyTextFile(QString srcPath, QString dstPath)
{
    QFile file(srcPath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return false;
    return writeTextFile(QString::fromUtf8(file.readAll()), dstPath);
}

bool writeTextFile(QString data, QString dstPath)
{
    QFile file(dstPath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return false;
    QTextStream stream(&file);
    stream << data;
    return true;
}

Upvotes: 3

Related Questions