【发布时间】:2020-02-10 20:58:17
【问题描述】:
我必须使用(自定义)二进制文件格式。数据对我的 RAM 来说太大了,我只需要导入其中的一小部分,进行一些计算并用新值覆盖/替换这部分(所以我不想导入所有内容,更改特定部分并编写所有内容返回)。
我尝试了seek 和writeBin 的组合,但这会生成一个小文件,其中我的新值以零开头:
fn <- tempfile()
writeBin(1L:3L, fn, size = 1L)
readBin(fn, what = "integer", size = 1L, n = 3L)
#> [1] 1 2 3
fh <- file(fn, "wb")
isSeekable(fh)
#> [1] TRUE
seek(fh, 1L, origin = "start", rw = "write")
#> [1] 0
# swap the sign of the second value
writeBin(-2L, fh, size = 1L)
close(fh)
readBin(fn, what = "integer", size = 1L, n = 3L)
#> [1] 0 -2
unlink(fn)
使用ab 模式附加到文件也无济于事:
fn <- tempfile()
writeBin(1L:3L, fn, size = 1L)
readBin(fn, what = "integer", size = 1L, n = 3L)
#> [1] 1 2 3
fh <- file(fn, "ab")
isSeekable(fh)
#> [1] TRUE
seek(fh, 1L, origin = "start", rw = "write")
#> [1] 3
# swap the sign of the second value
writeBin(-2L, fh, size = 1L)
close(fh)
readBin(fn, what = "integer", size = 1L, n = 3L)
#> [1] 1 2 3
unlink(fn)
我的预期输出是1 -2 3。
有没有办法在R 中做到这一点,还是我必须使用C 来实现它?
【问题讨论】:
标签: r binaryfiles seek