【问题标题】:How to replace a value in a binary file in R?如何替换R中二进制文件中的值?
【发布时间】:2020-02-10 20:58:17
【问题描述】:

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

我尝试了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 binaryfiles seek


    【解决方案1】:

    经过反复试验,我自己找到了解决方案:使用"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)
    

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

    ‘"wb"’ 以二进制模式打开写入。

    ‘"ab"’ 以二进制方式打开用于追加。

    '"r+"', '"r+b"' 开放读写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-23
      • 2011-04-14
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 2019-04-24
      • 2011-03-10
      相关资源
      最近更新 更多