Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way of determining that two file paths are referring to the same file object?

Tags:

c++

c

linux

windows

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.

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):

  1. On Linux, compare the inode from stat
  2. Use realpath (Is this Platform independent?)
  3. On Windows, compare strings on GetFullPathName
  4. On Windows, compare serial numbers and file index from GetFileInformationByHandle

What would be the cross-platform best solution? I'm writing this in C++, but I can drop down to C obviously.

like image 214
Mark Lakata Avatar asked Apr 07 '15 17:04

Mark Lakata


People also ask

How do I compare two path files?

Two file paths can be compared lexicographically in Java using the method java. io. File. compareTo().

How do you check if two paths are equal in Python?

path. samefile() method in Python is used to check whether the given two pathnames refer to the same file or directory or not. This is determined by comparing device number and i-node number of the given paths.

Which method is used for file path?

The getAbsolutePath() method is a part of File class. This function returns the absolute pathname of the given file object. If the pathname of the file object is absolute then it simply returns the path of the current file object. For Example: if we create a file object using the path as “program.


1 Answers

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)); 
like image 89
Barry Avatar answered Sep 22 '22 16:09

Barry