tcltar

Using tcl to get a list of files from tar.gz


I am trying to get a list of files from tar.gz file using tcl. I can extract the data from the tar.gz but how can I get the names of the file?

set f [open $tarFile]
zlib push gunzip $f
set data [read $f]
close $f

Solution

  • You are missing a couple of important things, primary of which is opening your file in binary mode.

    You need not just zlib but the tar package.

    package require zlib
    package require tar
    

    Then you can extract all the filenames:

    proc names.tar.gz tarFileName {
        set f [open $tarFileName {RDONLY BINARY}]
        zlib push gunzip $f
        set names [::tar::contents $f -chan]
        close $f
        return $names
    }
    

    You can display them easily by joining with a newline:

    puts [join [names.tar.gz $tarFileName] \n]
    

    Remember that if the file cannot be opened it will throw an error (that you should catch using either a try or catch construct).