I need to read from the file the data in binary form - first several int , then uint8_t , then something else.

I'm trying to use QFile::read() instead of fread() , but it turns out somehow scary:

 quint32 newNameLength; qint64 rCode = file.read(reinterpret_cast<char*>(&newNameLength), sizeof(quint32)); 

So generally you can do? If not, what is the most convenient analog for Qt for:

 uint32_t newNameLength; size_t rCode = fread(&newNameLength, sizeof(uint32_t), 1, f); 

?

    2 answers 2

    You can write a wrapper:

     size_t qread(void *ptr, size_t size, size_t count, QIODevice &file) { // QIODevice::read не может вернуть число большее, чем мы передали ему в maxSize return file.read(reinterpret_cast<char*>(&ptr), size * count); } 

    But it is better to use type safety C ++ and put everything into templates:

     // Вариант для массива template<typename T> size_t qread(T *out, size_t count, QIODevice &file) { return file.read(reinterpret_cast<char*>(&out), sizeof(T) * count); } // Вариант для одиночного элемента template<typename T> size_t qread(T &out, QIODevice &file) { return qread(&T, 1, file); } 
    • It may be possible, but this wrapper hides a little scary into a big one . Alien error messages will especially deliver if templates are used. In general, my example is the correct and adequate analogue of fread () ? - user294535
    • one
      эта обертка прячет маленькую страшность в большую - that's why I suggested the solution below through templates in case you don’t need an exact analogue of fread. мой пример является корректным и адекватным аналогом fread() - yes, it is. - ߊߚߤߘ
    • one
      the only thing to remember. that if you transfer a file between BE and LE, it will break ... if you don’t add the conversion after reading, of course ... - Fat-Zer

    Of course, you can, or even easier:

     quint32 newNameLength; qint64 rCode = file.read((char*)&newNameLength, sizeof(quint32)); 

    since it is clear that you just need an address, developers would have to immediately make the first argument as void * . Qt in general is often an address, as char * conveys, which is bad, unlike memcpy .