Important: Please read the Qt Code of Conduct -

How to prepend the data size to a file

  • I am saving the QAbstract tree model to a dat file.

    How can i prepend the size of total bytes to be written to the start of dat file.

    void saveTreeStructureToFile(const QModelIndexList &indexes , const std::string stdstrFilePath)
        QMimeData *mimeData = new QMimeData;
        QByteArray data; //a kind of RAW format for datas
        QDataStream stream(&data, QIODevice::WriteOnly);
        QList<TreeItem *> nodes;
        foreach(const QModelIndex &index, indexes) {
            TreeItem *node = getItem(index);
            if (!nodes.contains(node))
                nodes << node;
        stream << nodes.count();
        foreach(TreeItem *node, nodes) {
            buildTree(node, stream);
        mimeData->setData(s_treeNodeMimeType, data);
        std::string st = stdstrFilePath.substr(0, stdstrFilePath.size() - 3);
        const QString path = st.c_str();
        QFile file(path);;
        QDataStream out(&file);
        out << *mimeData;

  • Moderators

    hi @summit
    you have 2 possibilities,

    either calculate the size beforehand and write it first or write 0 in the first few bytes (4?) and overwrite them at the end.

    I you open your file in ReadWrite you can overwrite partially without loosing the rest. Just make sure to only change the reserved bytes

  • @J-Hilk Thank you very much , i have a question if i write 0 in the beginning how do i overwrite it with the size at the end.

    Can you please show me the code .

    suppose if i write 0 to the file

    stream << 0 // write 0 to the file and than write all other data
    stream << nodes.count();

    now how do i overwrite this data in the end

  • Moderators

    @summit actually looking at your code, the following should work

    QFile file(path);;
        QDataStream out(&file);
        out << static_cast<qint64 >(0) << *mimeData;
          file.write(static_cast<qint64 >(file.size()));

  • @J-Hilk said in How to prepend the data size to a file:

    static_cast<qint64 >(0)

    @J-Hilk Thank you very much , i am not able to prepend the size of the bytes.

  • Moderators

    @summit you couldn't be more vague, if you tried to.

    What error do you have?
    The code os untested from the top of my head, just fixed a typo there may be more

  • @summit
    @J-Hilk 's code looks good to me. You can also save closing and re-opening the file by changing the code that does that when finished writing your data to:

    file.write(static_cast<qint64 >(file.size()));

  • @J-Hilk sorry i wanted to write that i am able to prepend the file now and my problem is solved.

    unfortunately it was a type error from my side in my previous comment.

Log in to reply