Re: find a pattern in binary file
Ivan wrote:
On Jun 20, 1:11?pm, vizzz <andrea.visin...@gmail.com> wrote:
Hi there,
i need to find an hex pattern like 0x650A1010 in a binary file.
i can make a small algorithm that fetch all the file for the match,
but this file is huge, and i'm scared about performances.
Is there any stl method for a fast search?
Andrea
Hmmm... I had a look at this and ran accross a simple problem. How do
you read a binary file and just echo the HEX for byte to the screen.
#include <iostream>
#include <ostream>
#include <fstream>
#include <iterator>
#include <iomanip>
#include <algorithm>
#include <cassert>
class print_hex {
std::ostream * ostr_ptr;
unsigned int line_length;
unsigned int index;
public:
print_hex ( std::ostream & str_ref, unsigned int length )
: ostr_ptr( &str_ref )
, line_length ( length )
, index ( 0 )
{}
void operator() ( unsigned char ch ) {
++index;
if ( index >= line_length ) {
(*ostr_ptr) << std::hex << std::setw(2) << std::setfill( '0' )
<< (unsigned int)(ch) << '\n';
index = 0;
} else {
(*ostr_ptr) << std::hex << std::setw(2) << std::setfill( '0' )
<< (unsigned int)(ch) << ' ';
}
}
};
int main ( int argn, char ** args ) {
assert( argn == 2 );
std::ifstream in ( args[1] );
std::for_each( std::istreambuf_iterator< char >( in ),
std::istreambuf_iterator< char >(),
print_hex( std::cout, 25 ) );
std::cout << '\n';
}
The issue is the c++ read function doesn't return number of bytes
read... so on the last read into a buffer how do you know how many
characters to print?
Have a look at readsome().
Best
Kai-Uwe Bux