Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird behaviour with fread

I'm reading a binary uint32_t data from a file that indicates the size of the next binary block, after that I read that block but the reading pointer is "moving" wrong.

FILE* file = fopen("file.zip", "r");
long pointerA = ftell(file);
uint32_t streamSize = 0;
fread(reinterpret_cast<char*>(&streamSize), sizeof streamSize,1,file);
long pointerB = ftell(file);
char* zipData = new char[streamSize];
fread(zipData, sizeof(char),streamSize,file);

long pointerC = ftell(file);
fseek( file, pointerA + 4 + streamSize, SEEK_SET );
long pointerD = ftell(file);
qDebug()<<"streamSize"<<streamSize<<"Positions"<<pointerA<<pointerB<<pointerC<<pointerD;

PointerA is the original position, PointerB the position after reading that uint32_t, PointerC is the pointer after reading all that binary data and PointerD is just a check about what I suppose that should be the right behaviour.

Now let's see the debug:

streamSize 2653 Positions 151 156 4627 2808

Why the stream read position has moved too 4627 instead 2808?

Thank you in advance for any tip!

like image 412
Frank Escobar Avatar asked May 06 '26 21:05

Frank Escobar


1 Answers

Both users @alan-birtles and @remy-lebeau were right, I opened it as text instead binary that was the issue.

Unfortunatly I cannot mark this as solved.

PS. For begginers this means open file with "rb" instead "r".

like image 153
Frank Escobar Avatar answered May 08 '26 12:05

Frank Escobar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!