如何在 R 中读取 256 字节的块?

How to read a chunk of 256 bytes in R?

我是R语言新手。我有一个名为 testing.exe 的文件,我想在 R 中读取每 256 个字节。

我发现了这个网站 https://www.r-bloggers.com/example-10-1-read-a-file-byte-by-byte/ 适合我的情况:

finfo = file.info("testing.exe")
toread= file("testing", "rb")
alldata = readBin(toread, raw(256), n = finfo$size, endian="little")

但是所有数据都给我原始数据(0)。这是什么意思?我希望 alldata 会给出一系列字节值?我该如何修改代码?谢谢!

您真的无法在一个调用中全部读取一堆 256 字节的数据块。您可以阅读整个文件...

fname <- "testing.exe"
finfo <- file.info(fname)
toread <- file(fname, "rb")
alldata <- readBin(toread, raw(), n = finfo$size, endian="little")
close(toread)

或者您可以循环一次读取块

fname <- "testing.exe"
toread <- file(fname, "rb")
repeat {
  chunk <- readBin(toread, raw(), n = 256, endian="little")
  if (length(chunk)==0) break;
  print(chunk);
}
close(toread)