[SOLVED] QFile open error



  • Hi All,

    I am trying to read a simple text file through QFile and its returning "Unknown Error".

    @QFile file("E:/123.txt");
    if(file.exists()){
    qDebug()<<"File Exists";

    QFile f(QString("E:/123.txt"));
    if(f.isOpen()){
    f.close();
    }else{
    if(!f.open(QIODevice::ReadOnly | QIODevice::Text))
    qDebug()<<f.errorString();
    else
    qDebug()<<"It worked.";
    }
    }@

    On executing I get the following debug lines:
    @File Exists
    Unknown Error@

    What am I missing here?


  • Moderators

    Is there a specific reason you're using two different QFile objects?



  • Not really, that was mistake :(

    Updated my code to:

    @QFile file("E:/123.txt");
    if(file.exists()){
    qDebug()<<"File Exists";

    if(file.isOpen()){
    file.close();
    }else{
    if(file.open(QIODevice::ReadOnly | QIODevice::Text))
    qDebug()<<file.errorString();
    else
    qDebug()<<"It worked";
    }
    }@

    still having the same error.


  • Moderators

    Do you have read permission for the file on the file system? Does it work if you try to access a different file on a different drive?



  • Yes i have read permission for the file. In fact I have tried this on a number of files but it never worked.

    Tried this code both on windows and linux but encountered the same issue.


  • Moderators

    Oh... you're checking the return value of file.open() incorrectly. Ir returns true on success. Your errorString() and "It worked" cases are backwards.



  • Bull's eye... Thank you for pointing that out

    The code should have been like this:

    @if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    qDebug()<<file.errorString();
    else
    qDebug()<<"It worked";@


  • Moderators

    Sometimes it's the little things that bite you! Glad to help!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.