寻找一种使用 Nim 编程语言(版本 0.11.2)从 tar.gz 存档中读取文件的方法。说我有一个档案
/my/path/to/archive.tar.gz
以及该存档中的一个文件
my/path/to/archive/file.txt
我的目标是能够在 Nim 中逐行读取文件的内容。在 Python 中,我可以使用 tarfile 模块来完成此操作。 Nim 中有 libzip 和 zlib 模块,但文档很少,也没有示例。还有 zipfiles 模块,但我不确定它是否能够处理 tar.gz 档案。
在我公司的一个项目中,我们一直在使用以下模块,将 gzip 文件作为流公开:
import
zlib, streams
type
GZipStream* = object of StreamObj
f: GzFile
GzipStreamRef* = ref GZipStream
proc fsClose(s: Stream) =
discard gzclose(GZipStreamRef(s).f)
proc fsReadData(s: Stream, buffer: pointer, bufLen: int): int =
return gzread(GZipStreamRef(s).f, buffer, bufLen)
proc fsAtEnd(s: Stream): bool =
return gzeof(GZipStreamRef(s).f) != 0
proc newGZipStream*(f: GzFile): GZipStreamRef =
new result
result.f = f
result.closeImpl = fsClose
result.readDataImpl = fsReadData
result.atEndImpl = fsAtEnd
# other methods are nil!
proc newGZipStream*(filename: cstring): GZipStreamRef =
var gz = gzopen(filename, "r")
if gz != nil: return newGZipStream(gz)
但您还需要能够读取 tar 标头,以便在未压缩的 gzip 流中找到所需文件的正确位置。您可以包装一些现有的 C 库,例如libtar https://github.com/tklauser/libtar这样做,或者你可以推出自己的实施 https://stackoverflow.com/questions/2505042/how-to-parse-a-tar-file-in-c.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)