Version 0 of Example of reading and writing to a piped command

Updated 2005-04-20 16:21:22 by lwv

Recently on comp.lang.tcl someone was trying to get the following code to work:

 proc gzip {buf} {
      set fd [open "|gzip -c" r+]
      fconfigure $fd -translation binary -encoding binary
      puts $fd $buf
      flush $fd
      set buf [read $fd]
      close $fd
      return $buf
  }

Here's an altered version in an attempt to get it to work.

 #! /usr/tcl84/bin/tclsh

 proc gzip {buf} {
      set fd [open "|gzip -c" "r+"]
      fconfigure $fd -translation binary -encoding binary
      puts -nonewline $fd $buf
        puts "output finished to gzip"
      flush $fd
        puts "flush finished to gzip"
      set buf [read $fd]
        puts "read finished from gzip"
      close $fd
      return $buf
  }

 proc gunzip {buf} {
      set fd [open "|gzip -d" "r+"]
      fconfigure $fd -translation binary -encoding binary
      puts -nonewline $fd $buf
      flush $fd
      set buf [read $fd]
      close $fd
      return $buf
  }

 set a [gzip "This is a test"]
 puts "finish compression"
 set b [gunzip $a]
 puts "finish uncompression"

 puts $b

Alas, it still doesn't work. The output and flush debug statements appear. But the message after the read doesn't appear.

Now, an alternative version of the command was proposed:

 proc gzip {buf} {
      return [exec gzip -c << $buf]
 }

However, that version doesn't demonstrate the method to read and write from a piped command. So I'm hoping that someone comes along with a fix for the initial code.


See also open, pipe, gzip.


Category Example