How can I read a gzipped file in TCL?

2019-07-07 07:57发布

I have a file with .gz extension. When I try to read and print the file with following TCL commands I can't read the file even though I am able to see the contents in the VI editor.

I tried with the following TCL code:

set of [glob *.gz ]
set op [open "$of" r]
set file_data [read $op]
set data [split $file_data "\n"]
foreach line $data {
    puts " $line"
}

标签: tcl gzip
2条回答
你好瞎i
2楼-- · 2019-07-07 08:26

In Tcl 8.6, you have built-in support for this so you can do:

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

The zlib push gunzip just attaches a suitable uncompressing transform to the channel.

In 8.5 and before, you're best to read from a pipeline with zcat or gzcat (depending on platform details:

set f [open "|gzcat $filename"]
set data [read $f]
close $f

The down-side is that that's nowhere near as portable.

查看更多
在下西门庆
3楼-- · 2019-07-07 08:42

Read from Pipeline

Given a file named foo.gz, you could use something like the following:

set pipeline [open "| zcat foo.gz"]
set data [read $pipeline]
close $pipeline

This obviously relies on an external gzip utility. There may be a pure TCL solution, but this is fast and easy if your environment has a gzip executable.

查看更多
登录 后发表回答