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

Ivan Krylov |kry|ov @end|ng |rom d|@root@org
Tue May 21 12:15:36 CEST 2024


В Tue, 21 May 2024 11:29:33 +0200
Laurent Rhelp <laurentRHelp using free.fr> пишет:

> 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))

That's because seek() returns the previous position ("before any
move", the one that the help page calls "current"), not the one after
the seek. Fortunately, calling seek(origin = "start") twice with the
same offset doesn't break anything.

> # we are on position 6
> pos <- seek(con_in,0,origin="current")

That's strange. You started at offset 2 and read three bytes. You
should be at offset 5 at this point. For me, seek() returns 5 here, not
6.

> bytes = readBin(con=con_in, what="raw",n = 1)

But after this, we should be on position 6.

> writeBin(  my_string, con=con_in, useBytes = FALSE)

It's described in help(seek) that R maintains two different pointers
for reading and writing a file. You have been reading it, advancing the
read pointer to 6, but the write pointer stayed at offset 0.

Try seek(con_in, seek(con_in, 0, 'current', 'read'), 'start', 'write')
to set the write pointer to the read pointer before issuing writes.
This seems to give me the expected result.

-- 
Best regards,
Ivan



More information about the R-help mailing list