Raeding and searching byte array from file
Apr 14, 2020 at 1:50pm UTC
Hi,
I'm writting a simple code to find in wich offset of a given file there is an array of bytes.
For example, searching 0x66 0x7C 0x1B 0xAA in a file. I wrote the next code, that it's working, but I want to know if this is the right way or if there is any other more eficient way to do that.
This is the function to read a file, always assuming you have enought memory to load it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
char * read_block_2(std::uint32_t offset, std::uint32_t length, std::string const & filename)
{
char * data = new char [length];
std::ifstream is(filename, ios::in | ios::binary | ios::ate);
if (is.is_open())
{
is.seekg(offset);
is.read(data, (ifstream::pos_type)length);
is.close();
}
else {
cout << "error" ;
}
return data;
}
And this is my "searcher":
1 2 3 4 5 6
for (int i = offset; i < offset + lenght; i+=1) {
if (a[i] == 0x66 && a[i + 1] == 0x7C && a[i + 2] == 0x1B && a[i + 3] == 0xAA) {
cout << "found at: " ;
cout << i << "\n" ;
}
}
And my other variant:
1 2 3 4 5 6 7
for (int i = offset; i < offset + lenght; i+=1) {
unsigned long tag= a[i + 3] << 24 | a[i + 2] << 16 | a[i + 1] << 8 | a[i];
if (tag == 2853928038){
cout << "found at: " ;
cout << i << "\n" ;
}
}
Thanks in advance!
Last edited on Apr 14, 2020 at 1:50pm UTC
Apr 14, 2020 at 2:31pm UTC
1. Your search loop should stop at length-3, otherwise you're stepping off the end of your data.
2. Use memcmp() to simplify the code.
Apr 14, 2020 at 2:53pm UTC
Thanks for the first observation xD
This is you mean?
1 2 3 4 5 6 7
for (int i = offset; i < lenght - 3; i += 1) {
char find[] = "\x66\x7c\x1b\xaa" ;
int flag = memcmp(&a[i], &find, 4);
if (flag == 0) {
cout << "found" << "\n" ;
}
}
Thanks ;)
Last edited on Apr 14, 2020 at 2:54pm UTC
Apr 14, 2020 at 3:17pm UTC
Yes, something like that.
But you can move the find array outside the loop, it never changes.
Topic archived. No new replies allowed.