Over a million developers have joined DZone.

Using Mmap To Do A Global Search And Replace On Windows

·
// 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
}
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}