如何替换 R 中二进制文件中的值?

How to replace a value in a binary file in R?

我必须使用(自定义)二进制文件格式。数据对于我的 RAM 来说太大了,我只需要导入其中的一小部分,进行一些计算,然后 overwrite/replace 这部分使用新值(所以我不想导入所有内容,更改特定部分和写回所有内容)。

我尝试了 seekwriteBin 的组合,但这会生成一个小文件,我的新值前面加上零:

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+b"支持替换数据。

fn <- tempfile()

writeBin(1L:3L, fn, size = 1L)
readBin(fn, what = "integer", size = 1L, n = 3L)
#> [1] 1 2 3

fh <- file(fn, "r+b")
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]  1 -2  3

unlink(fn)

我之前没有尝试过这个,因为 ?fileModes 的文档没有提供这个信息:

‘"wb"’ Open for writing in binary mode.

‘"ab"’ Open for appending in binary mode.

‘"r+"’, ‘"r+b"’ Open for reading and writing.