New content are available at http://tis-method.org/. All articles from this site will be moved to the new location.

среда, 29 сентября 2010 г.

Scanning file using boost::regex [windows specific]

Task statement
Make light wrapper around file on disk to work with boost::regex.

"Brute force"
Open file, read all data into a string, use boost::regex.

File mapping
Represent file as byte-array, using file mapping into a memory.
Below, possible solution.
template < class charT >
class basic_regex_file< charT, z3d::platform::windows >
{
public:
 ///
 typedef charT
  char_t;
 ///
 typedef std::basic_string< char_t >
  string_t;
 ///
 typedef char_t*
  iterator;
 ///
 typedef char_t const*
  const_iterator;
 ///
 typedef char_t*
  view_t;
 ///
 explicit basic_regex_file( string_t const& sname ) : 
 mapping( 0 )
  , view( 0 )
  , size_lo( 0 )
  , size_hi( 0 )
 {
  HANDLE file = open_file( sname, boost::mpl::identity< char_t >() );
  this->mapping = CreateFileMapping( file, NULL, PAGE_READONLY, 0, 0, NULL );
  this->view  = reinterpret_cast< view_t >( MapViewOfFile( this->mapping, FILE_MAP_READ, 0, 0, 0 ) );
  //
  if ( ( file != INVALID_HANDLE_VALUE ) && ( this->mapping != NULL ) && ( this->view != NULL ) )
  {
   this->size_lo = GetFileSize( file, &(this->size_hi) );
  }
  CloseHandle( file );
 }
 ~basic_regex_file()
 {
  if ( this->view != NULL )
  {
   ::UnmapViewOfFile( this->view );
  }
  if ( this->mapping != NULL )
  {
   ::CloseHandle( this->mapping );
  }
 }
 ///
 const_iterator begin() const
 { return ( &( this->view[0] ) ); }
 ///
 const_iterator end() const
 { return ( &( this->view[ this->size_lo / sizeof( char_t ) ] ) ); }
 ///
 operator bool() const
 { return ( ( this->view != 0 ) && ( this->size_lo || this->size_hi ) ); }

private:
 ///
 HANDLE
  mapping;
 ///
 view_t
  view;
 ///
 DWORD
  size_lo;
 ///
 DWORD
  size_hi;
 ///
 HANDLE open_file( string_t const& sname, boost::mpl::identity< wchar_t > )
 { return CreateFileW( sname.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); }
 ///
 HANDLE open_file( string_t const& sname, boost::mpl::identity< char > )
 { return CreateFileA( sname.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); }
};
typedef basic_regex_file< char, z3d::platform::windows > win_regex_file;
typedef basic_regex_file< wchar_t, z3d::platform::windows > wwin_regex_file;

How to use
z3d::util::win_regex_file wrf( "file.txt" );
if ( wrf && boost::regex_match( wrf.begin(), wrf.end(), boost::regex( ".*ABC.*" ) ) )
{
 // found
}

Where to find
Use classes located in z3d/util/regex-file.hpp from z3d.



Комментариев нет:

Отправить комментарий