Karim Abdel Hamid Karim Abdel Hamid - 2 months ago 6
C++ Question

Large ints being misread/miswritten to binary file

I'm trying to create a saving/loading system. While I've created tons of ASCII parsers, I'm not so used to binary ones. Currently, if I pass a small value, say 2, it works. So does. 11. 10 returns 13, and 412 returns -100. I'm using buffers which I can precalculate the size of before reading, but I'm getting incorrect values anyways.

This is part of a saver method:

FILE *ptr_myfile;

ptr_myfile = fopen("data.sav", "wb");
uint32_t bufferSize = 4;
char *writeBuffer = (char*)malloc(bufferSize);

int value = 412;
memcpy(&writeBuffer, &value, sizeof(value));

fwrite(&writeBuffer, sizeof(char), sizeof(writeBuffer), ptr_myfile);


And this is part of a loader method:

FILE *ptr_myfile;

ptr_myfile = fopen("data.sav", "rb");

//Get file length
fseek(ptr_myfile, 0, SEEK_END);
unsigned long fileLen = ftell(ptr_myfile);
fseek(ptr_myfile, 0, SEEK_SET);

char *buffer = (char *)malloc(fileLen + 1);
if (!buffer) {
fprintf(stderr, "Memory error!");

fread(buffer, fileLen, 1, ptr_myfile);

printf("%i\n", (int)buffer[0]);


Thanks in advance!

char *buffer = (char *)malloc(fileLen + 1);

Buffer is an array of chars.

printf("%i\n", (int)buffer[0]);

This prints the value of buffer[0], which is a single character, after casting it to an int.

Your code that wrote the binary file did not manage to stuff an entire int into the first character in the file, obviously. It memcpyed the int into a character buffer.

To read this back, the process is reversed, exactly: memcpy() the character buffer into an int variable.