检查两个文件路径是否解析为同一个文件

问题描述 投票:0回答:2

假设我有三个文件路径:

setwd("C:/superlongdirname")
files <- c("C:/superlongdirname/myfile.txt", "C:\\SUPERL~1\\myfile.txt", "./myfile.txt")

这些都指向同一个文件。给定对同一文件的多个引用,我如何检查它们确实引用了 R 中的同一个文件?

r windows filepath
2个回答
5
投票

使用完整版本的文件路径并进行比较:

normalizePath(files[1]) == normalizePath(files[2])

0
投票

我将其发布为答案,因为我没有足够的声誉来发表评论。这是我对同一问题的回答的副本这里

如果同一个文件有多个合法文件路径,

normalizePath
fs::path_norm
都不起作用。例如,在 HPC 中,
~/scratch/somedir/file
/scratch/username/somedir/file
等通常指同一个文件。

在这些情况下,我必须使用 bash 的

[[ FILE1 -ef FILE2 ]]
测试,如 answer here 中所述。正如那里提到的,
-ef
运算符可能不符合 POSIX 标准,但可以在大多数 shell 中工作,并且看起来相当便携。

这里是一个使用

R
system()
中执行此测试的函数,它返回命令的退出代码。退出代码
0
表示测试正确。

check_paths_equal <- function(path1, path2){
  cmd <- sprintf("[[ %s -ef %s ]]", path1, path2)
  exit_code <- system(cmd)
  return(exit_code==0)
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.