Search code examples
c++qtqbytearray

How to read n bytes of a file in QT C++?


Hi im new to Qt and im trying to read for example the first 4 bytes of my .txt file and show it. I've been searching and figure that QbyteArray may help me best in this situation. so I really like to know how can i read the first 4 bytes of my file with QbyteArray? (appreciate if u write any example code)


Solution

  • Assuming your code contains something like this:

    QFile file{ "path/to/file.txt" };
    
    • You can read a number of bytes from a file with file.read(n), assuming n to be a number of bytes. you can also use file.readAll() to get the entire thing

    • for more advanced input/output operations, you can use the QTextStream class as such:

      QFile file { "path/to/file.txt" };

      QTextStream stream { &file }; (This is a stream that can read and write data to the provided device, here, a file.)

    For more info, see here:

    https://doc.qt.io/qt-6/qfile.html for QFile

    https://doc.qt.io/qt-6/qtextstream.html for QTextStream