How to save binary file from QByteArray rather than QTextStream



  • I am working on a binary file editor (not quite a hex editor).
    I started with the mdi example supplied with Qt.
    I changed the opening of the file to binary.
    But don't know what I'm doing to use a QByteArray instead of QString.
    So here is the save file function with my failed attempt indicated:

    bool MdiChild::saveFile(const QString &fileName)
    {
        QFile file(fileName);
        if (!file.open(QFile::WriteOnly)) {  // was | QFile::Text)) {
    //      ...
            return false;
        }
    
    //    QTextStream out(&file);  // What I had
        QByteArray out(&file);   // What I want
        out << toPlainText();
    
        setCurrentFile(fileName);
        return true;
    }
    

    Gives error:

    /home/.../mdichild.cpp:120: error: no matching function for call to 'QByteArray::QByteArray(QFile*)'
         QByteArray out(&file);
                             ^
    

    I understand that QByteArray is not a stream, but don't know what to do here.
    Also not yet comfortable knowing what can be overloaded or modified in classes -- for QPlainTextEdit()
    Thank you.



  • Instead of using QByteArray as a type of 'QTextStream' you should probably do it this way:

    {
        QFile file(fileName);
        if (!file.open(QFile::WriteOnly)) {  // was | QFile::Text)) 
        {
           //      ...
            return false;
        }
        // assuming you need a QByteArray()
        QByteArray data(this->toPlainText().toLatin1());
        file.write(data);
    
        // or cut out the middle man
        file.write(this->toPlainText().toLatin1());
        
        setCurrentFile(fileName);
        return true;
    }
    

    Note: If you are looking to convert the binary file data to and from hexadecimal QByteArray has functions 'toHex()' and 'fromHex()' which work quite well.



  • @Rondog Thank you. After a good nap I figured out what I needed. Your post confirmed it. (I didn't need the toLatin1(); either.)


Log in to reply
 

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