确定两个文件路径引用同一个文件对象的最佳方法是什么?
我想编写一个单元测试来检查两个文件路径是否相同,但我不想假设字符串表示是相同的.
I want to write a unit test that checks that two file paths are equivalent, but I don't want to assume that the string representation is the same.
例如,在 Linux 上,在一种情况下路径中可能存在符号链接,而在另一种情况下则没有.在 Windows 上,一个可能有驱动器符号 (X:\foo
),另一个可能有网络符号 (//serverX/foo
).最复杂的是,该文件可能是在 Linux 上编写的 NFS 共享(在 /path/to/file
语法中)并在 Windows 上使用 DOS 语法(X:\to\file
)验证,其中 X:
是一个 NFS 挂载到 /path
.
For example, on Linux there could be symlinks in the path in one case and not in the other. On Windows, there could be drive notation on one (X:\foo
) and network notation on the other (//serverX/foo
). And most complicated, the file may have been written on Linux on an NFS share (in /path/to/file
syntax) and verified on Windows using DOS syntax (X:\to\file
) where X:
is a NFS mount to /path
.
一些想法(在 * 上找到,但不统一):
Some ideas (found here on Stack Overflow, but not unified):
- 在 Linux 上,比较
stat
- 使用
realpath
(是这个平*立?) - 在 Windows 上,比较
GetFullPathName
上的字符串 - 在 Windows 上,比较来自
GetFileInformationByHandle
跨平台的最佳解决方案是什么?我是用 C++ 写的,但我显然可以降级到 C.
What would be the cross-platform best solution? I'm writing this in C++, but I can drop down to C obviously.
您可以查看 Boost.Filesystem
库.具体来说,有一个方法 equivalent
似乎完全符合您的要求:
You could check out the Boost.Filesystem
library. Specifically, there is a method equivalent
that seems to do exactly what you are looking for:
using namespace boost::filesystem;
path p("/path/to/file/one");
path q("/sym_link/to/one");
assert(equivalent(p, q));