QFile - File not writing on OS X

  • Hello, I am trying to use QFile to write / read a simple text file and I am getting "Unknown error" and error number 0. The file does get created but no data is writing to it. I have the same problem trying to open and read a file. Same error.

    The only way I can get it to write to the file is if I don't specify a path like so:

        QFile mFile("test.txt");

    But when I do this, the file ends up sitting inside the applications package contents: myFileIO.app/Contents/MacOS/test.txt

    So I'd like to figure out how to get this to read/write to a path outside of the location of the executable itself.

    Here is my test code:

    void Write ()
        QFile mFile("/Users/Shared/test.txt");
        if(!mFile.open(QFile::WriteOnly) | QFile::Text){
            qDebug() << "Could not open file for writing";
            qDebug() << "exists?              " << mFile.exists();
            qDebug() << "writable?            " << mFile.isWritable();
            qDebug() << "permissions?   " << mFile.permissions();
            qDebug() << "errors?              " << mFile.errorString();
            qDebug() << "errnum?              " << mFile.error();
        QTextStream out(&mFile);
        out << "hello world";

    And this is the output i am getting:

    Could not open file for writing
    exists?               true
    writable?             true
    permissions?    QFlags(0x4|0x40|0x200|0x400|0x2000|0x4000)
    errors?               "Unknown error"
    errnum?               0
    QIODevice::write (QFile, "/Users/Shared/test.txt"): device not open

    Any ideas?



  • Because you closed your mFile before QTextStream write:

    mFile.close(); // << Remove that
    QTextStream out(&mFile);

  • In addition to closing the file:

    • the path should be verified. A typical user path name is something like '/Users/<user-name>/'. Maybe a QFileDialog should be used to pick a file name to write would be better (or use the home path).

    • the test to open the file is wrong:

    if(!mFile.open(QFile::WriteOnly) | QFile::Text){
    \\ should be
    if(!mFile.open(QFile::WriteOnly | QFile::Text)){
    • you should call 'flush' on the QTextStream and not on 'mFile'. I have seen issues where you might have the text file truncated if used the way it is. If you happen to have QTextStream go out of scope it works fine then.

  • That did it.. Thanks.

Log in to reply

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