Take this example, where we use the default value of the open
parameter of the file
function:
❯ R
> fh <- file("test.txt")
> writeLines("1", fh)
> writeLines("2", fh)
> close(fh)
> quit()
The resulting file only contains the last line:
❯ cat test.txt
2
which seems a wrong behavior, I would expected both lines to be present.
Now take this example when we set open="w"
:
❯ R
> fh <- file("test.txt","w")
> writeLines("1",fh)
> writeLines("2",fh)
> close(fh)
> quit()
Now both lines are correctly written:
❯ cat test.txt
1
2
The documentation of file
says:
The mode of a connection is determined when actually opened, which is deferred if ‘open = ""’ is given.
So it looks like the mode is set by writeLines
. Its docs say:
If the connection is open it is written from its current position. If it is not open, it is opened for the duration of the call in ‘"wt"’ mode and then closed again.
And the docs for file says that wt
is equivalent to w
:
‘"w"’ or ‘"wt"’ Open for writing in text mode.
So since the two ways open the file in the same mode, I don't understand why they give different results.