tags:

views:

219

answers:

2

Hi,

I am writing a program in Ruby which will search for strings in text files within a directory - similar to Grep.

I don't want it to attempt to search in binary files but I can't find a way in Ruby to determine whether a file is binary or text.

The program needs to work on both Windows and Linux.

If anyone could point me in the right direction that would be great.

Thanks,

Xanthalas

+1  A: 
gem install ptools
require 'ptools'
File.binary?(file)
Xanthalas
+1  A: 

libmagic is a library which detects filetypes. For this solution I assume, that all mimetype's which start with text/ represent text files. Eveything else is a binary file. This assumption is not correct for all mime types (eg. application/x-latex, application/json), but libmagic detect's these as text/plain.

require "filemagic"

def binary?(filename)
  begin
    fm= FileMagic.new(FileMagic::MAGIC_MIME)
    !(fm.file(filename)=~ /^text\//)
  ensure
    fm.close
  end
end
johannes