3

I would like to read data from an input file or STDIN - the input data may be gzipped.

For files this can be done with Zlib::GzipReader like this:

require 'zlib'

ios = File.open(file, mode='r')

begin
  ios = Zlib::GzipReader.new(ios)
rescue
  ios.rewind
end

ios.each_line { |line| puts line }

However, I fail to get the detection of zipped data from STDIN right:

require 'zlib'

if STDIN.tty?
  # do nothing
else
  ios = STDIN

  begin
    ios = Zlib::GzipReader.new(ios)
  rescue
    ios.rewind
  end
end

ios.each_line { |line| puts line }

The above works with gzipped data in STDIN, but regular data results in this:

./test.rb:14:in `rewind': Illegal seek - <STDIN> (Errno::ESPIPE)
        from ./test.rb:14:in `rescue in <main>'
        from ./test.rb:11:in `<main>'

So, if I cannot rewind STDIN, how do I test if data in STDIN is zipped or not?

Cheers,

Martin

1
  • Thank you :o). I discovered how nifty this forum is from biostars.org.
    – maasha
    May 22, 2011 at 8:58

1 Answer 1

1

Load data from STDIN into temporary file and only then parse it

require 'tempfile'

tf = Tempfile.new('tmp')

while $stdin.gets do
   tf.puts $_
end

tf.rewind
1
  • 1
    I am working with quite a lot of data here and would like to avoid the temporary file solution. It strikes me that GzipReader must read in a chunk of data in a buffer and unzip that if possible - or raise an error. GzipReader ought to have some method to test if the buffer contains zipped data - or return the buffer as an IO object.
    – maasha
    May 22, 2011 at 8:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.