[R] wrtiteBin in conjunction with seek : the position in the file is not good when writing

Laurent Rhelp |@urentRHe|p @end|ng |rom |ree@|r
Tue May 21 11:29:33 CEST 2024


Dear RHelp-list,

  I want to write at a specific position in a file without reading all 
the file
because it is very large and I cannot read it in my RAM. But I miss 
something
about the use of the command writeBin in conjunction with seek. In the 
example bellow the seek
commands works well with the readBin command but not with writeBin, the 
writeBin
command write from the beginning of the file and not from the current 
position
and however in the doculentation it is written:
   If the connection is open it is read/written from its current position.
Thank you
Best regards
Laurent


Here is the tiny example:

The file_test.txt before:
1234567890
1234567890

The file_test.txt after:
  AA AA7890
1234567890

The file should have been like that:
123456 AA AA1234567890

## open the file in read/write mode + binary
fname <- file.path(".","txt","file_test.txt")
con_in <- file(fname,"r+b")
# move on 2 bytes
pos <- seek(con_in,2,origin="start")
# We have to repeat the command to return the good amount of read bytes
print(paste0("pos is not equal to 2, pos = ",pos))
pos <- seek(con_in,2,origin="start")
print(paste0("Now pos is equal to 2, pos = ",pos))

## reading 3 characters
bytes = readBin(con=con_in, what="raw",n = 3)
my_number <- as.numeric(readBin(bytes,"character"))
print(my_number)
# we are on position 6
pos <- seek(con_in,0,origin="current")
print(paste0("pos = ",pos))
bytes = readBin(con=con_in, what="raw",n = 1)
my_number <- as.numeric(readBin(bytes,"character"))
print(my_number)
my_string <- charToRaw(sprintf(paste('%',3,'s',sep=''),"AA"))
writeBin(  my_string, con=con_in, useBytes = FALSE)
writeBin(  my_string, con=con_in, useBytes = FALSE)
close(con_in)



More information about the R-help mailing list