file - 从 Nim 中的 tar.gz 存档中读取文件

标签 file gzip tar nim-lang

寻找一种使用 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/

相关文章:

ruby - 在 Ruby 中下载远程文件之前如何获取它的 mtime?

performance - 在 Couchdb 中压缩(Gzip 或 Deflate)显示、列表和 View

Node.js - 如何处理流错误事件

java - 即使在其他平台上运行,也使用 Maven 程序集插件设置 Linux 文件权限?

linux - 如何解压子目录?

Java读取文件并将字符串存储到数组中

java - 删除文件(奇怪的扩展名)

python - 在文本文件中查找新行字符

Python gzip CRC 检查失败

linux - 变量作为 SunOs 5.10 中的 Tar 文件名