寻找一种使用 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 header ,以便在未压缩的 gzip 流中找到所需文件的正确位置。您可以包装一些现有的 C 库,如 libtar这样做,或者你可以 roll your own implementation .
关于file - 从 Nim 中的 tar.gz 存档中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33082639/