Solved QFile - pos() not equal to sum of bytes read?
-
Hi,
I'm pretty new to qt (and c++ in general), so maybe this is not a qt specific "problem".
I have a binary file that I open and I read a few bytes. After that I read a few more bytes in a loop. Subsequently, as far as I understood, file.pos() should be equal to all the bytes I have read so far, but for a few files, there is a mismatch.code snippet:
[CODE] char buffer[255]; qint64 bytesRead; QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){ qDebug() << "could not open" << fileName; return -1; } bytesRead = file.read(buffer, 16); if(bytesRead != 16){ qDebug() << "mismatch bytes read" << bytesRead << " != " << 16; } if(file.pos() != 16){ qDebug() << "mismatch" << file.pos() << " != " << 16; } ... for (int i = 0; i < 7; i++) { bytesRead = file.read(buffer, 24); ... if(bytesRead != 24){ qDebug() << "mismatch bytes read" << bytesRead << " != " << 24; } if(file.pos() != (16 + (i+1)*24)){ qDebug() << "mismatch" << file.pos() << " != " << (16 + (i+1)*24); } } file.close()
and the output is
mismatch 185 != 184
This happens not on all files, so I am wondering what I am doing wrong...
Any help or pointer is appreciated! -
file.pos()
returns the current position, not the sum of all bytes read.
Any chance that something went wrong in these [...] lines? -
@QJames
You are opening forQIODevice::Text
. I can't recall how each ofpos()
andread()
count, you should check whether one counts e.g.\r\n
as 1 while the other does not? Perhaps the difference between files is down to the "newline" recognition/counting? Certainly remove theQIODevice::Text
and compare. IIRC, text read makespos()
only take on certain values/validity anyway, there's something in the docs... -
@Pl45m4 said in QFile - pos() not equal to sum of bytes read?:
file.pos()
returns the current position, not the sum of all bytes read.
Any chance that something went wrong in these [...] lines?sure, but it should be the same, shouldn't it? the position should move along with bytes written/read.
@JonB said in QFile - pos() not equal to sum of bytes read?:
@QJames
You are opening forQIODevice::Text
. I can't recall how each ofpos()
andread()
count, you should check whether one counts e.g.\r\n
as 1 while the other does not? Perhaps the difference between files is down to the "newline" recognition/counting? IIRC, text read makespos()
only take on certain values/validity anyway, there's something in the docs...thank you, that was it!!
Removing the QIODevice::Text flag solved it.