DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Daniel has posted 5 posts at DZone. View Full User Profile

Using Mmap To Do A Global Search And Replace On Windows

05.13.2008
| 3321 views |
  • submit to reddit
        // Use win32-mmap to do a global search and replace on Windows

require 'win32/mmap'
require 'windows/msvcrt/buffer'
include Windows::MSVCRT::Buffer

Strlen = API.new('strlen', 'L', 'L', 'msvcrt')
Strstr = API.new('strstr', 'LP', 'L', 'msvcrt')

Dir["**/*.rb"].each{ |f|
   p f
   Win32::MMap.new(:file => f) do |addr|
      old_str = 'some_old_string'
      old_len = old_str.length
      new_str = 'some_other_string'
      new_len = new_str.length

      ptr1 = ptr2 = ptr3 = Strstr.call(addr,old_str)

      while ptr1 && ptr1 != 0
         ptr2 += new_len
         ptr3 += old_len
         memmove(ptr2, ptr3, 1 + Strlen.call(ptr3))
         memcpy(ptr1, new_str, new_len)
         ptr1 = ptr2 = ptr3 = Strstr.call(ptr2,old_str)
      end
   end
}