[Rd] Questions on "\" vs "/" on Windows

Prof Brian Ripley ripley at stats.ox.ac.uk
Sat Aug 20 16:54:45 CEST 2005


On Sat, 20 Aug 2005, Seth Falcon wrote:

> A recent thread on R-help reminded me of some questions I have
> regarding the path separator on Windows.
>
> The thread: [R] using paste and "\" to create a valid filename
>
> The question:
>
> What are the use-cases where "\" is required for paths passed as
> character vectors from within R?

1) A few Windows utilities require \, so we try to always use \ in paths 
exported e.g. when using system()/shell().  No Windows API call does, it 
appears.

Uwe Ligges reported that on his system Mozilla 1.7.3 did in file:// URLs, 
(although it did not on mine) so we altered the HTML help print method

2) Some Windows users file bug reports when they see / in a path.  So to 
keep them happy (or at least out of our hair) we tend to use \ in 
messages, and in normalizePath().

> My experience has been that "/" always works and "\" often fails due
> to escaping issues (the user's fault).  A pathalogical example
> that I _have_ encountered due to temp file naming on Windows:
>
>  > badpath <- "foo\\2\\bar"
>  > root <- "c:\\HERE\\file.txt"
>  > gsub("HERE", badpath, root)
>  Error in gsub("HERE", badpath, root) : invalid backreference 2 in regular expression
>
> Using file.path is recommended as a best practice, but AFAICT, it
> forces "\" on Windows.

Wrong (how did you 'T'?).  On Windows:

> file.path("foo", "bar")
[1] "foo/bar"

> Why not have file.path dynamically read .Platform$file.sep
> so that in code that uses file.path one could modify
> .Platform$file.sep and change the behavior of all subsequent file.path
> calls?

It _does_ dynamically read .Platform$file.sep, and it has an fsep argument 
so you can do

file.path("foo", "bar", fsep="\\")

Beware though of namespaces: you would need to change .Platform$file.sep 
in the base namespace (which you can do):

> .Platform$file.sep <- ":"
> assignInNamespace(".Platform", .Platform, "base")
> file.path("foo", "bar")
[1] "foo:bar"

> Python's os.path.join function behaves similarly to R's: changing
> os.sep doesn't change the behavior of os.path.join.
> .Platform$file.sep = "/" and change the behavior of all subsequent
> calls.
>
> With both languages, I've found that for glue-code type tasks,
> sticking to "/" on Windows is much easier and I've been frustrated by
> the built-in path handling function.

Why, as R's uses "/"?  I wonder if you did consult the help pages before 
posting ....

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-devel mailing list