In C, I first opened a binary file like this---
FILE *BINfile = fopen("./tmp.bin", "rb+");
Then I transferred the data into an unsigned char array (typedef as byte) like this---
(Side note; I'm an amateur so I'm more comfortable with arrays)
typedef unsigned char byte;
size_t GetFileSize (FILE *file) {
fseek(file, 0, SEEK_END);
size_t Size = ftell(file);
rewind(file);
return Size;
}
byte BinFileArray[GetFileSize(BINfile)];
size_t BinReadAmount = fread(BinFileArray, 1, GetFileSize(BINfile), BINfile);
Then I wrote a function to find an int value in that bin array by first converting the int to an byte array---
size_t BinaryOffsetFinder (byte Array[], size_t ReadAmount, size_t Target) {
size_t index=0;
byte charTarget[sizeof(Target)];
byte buffer[sizeof(charTarget)];
memcpy(charTarget, &Target, sizeof(Target));
for (int i=0; i<ReadAmount; i++) {
for (int j=0; j<sizeof(buffer); j++) {
buffer[j]=Array[i+j];
}
if (buffer==charTarget) {
index=i;
break;
}
}
return index;
}
Then I ran it like this---
printf("\n%d", BinaryOffsetFinder(BinFileArray, BinReadAmount, 5019));
//I know the file has 5019 in it cause I'm modding a binary game file. Verified using ImHex
And I'm pretty confident that a lot of stuff is really wrong. Not because I'm getting 0 every time, but I seriously lack concepts here. Someone please point out the conceptual errors.
mainand all#includedirectives. You are explaining the individual code snippets nicely, so it would be good to keep them. But it would also be good to additionally post a compilable program that reproduces the issue, which other people can test. This program should use the code snippets that you posted.printf("\n%d", BinaryOffsetFinder(BinFileArray, BinReadAmount, 5019));is incorrect since the functionBinaryOffsetFinder()returnssize_twhich needs the format specifier%zunot%d. Also as a matter of style it's better to end with a newline than to begin with one.int8_t,int16_t,int32_tandint64_t, instead ofintorsize_t. That way, it is clearer what size you expect the integers to be. Note that using these data types requires#include <stdint.h>.fseek(file, 0, SEEK_END); size_t Size = ftell(file);is bug-prone and not portable. See How do you determine the size of a file in C?