[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 16:35:54 CEST 2024


It works !!

Thank you VERY much because I didn't understand the rw argument for the 
seek command and endeed it is explained:

File connections can be open for both writing/appending, in which 
case*R*keeps separate positions for reading and writing. 
Which|seek|refers to can be set by its|rw|argument: the default is the 
last mode (reading or writing) which was used. Most files are only 
opened for reading or writing and so default to that state. If a file is 
open for both reading and writing but has not been used, the default is 
to give the reading position (0).

Best regards

Laurent

Le 21/05/2024 à 12:15, Ivan Krylov a écrit :
> В 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.
>
	[[alternative HTML version deleted]]



More information about the R-help mailing list