Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

How do I portably determine if two filenames refer to the same file?

by jcb (Parson)
on Aug 16, 2019 at 03:31 UTC ( #11104545=categorized question: print w/replies, xml ) Need Help??
Contributed by jcb on Aug 16, 2019 at 03:31 UTC
Q&A  > files


On POSIX systems, and possibly others, a file can have multiple names (known as hardlinks) or can itself contain the name of another file in such a way that the system substitutes that other file for most operations on a file (these are symlinks). For various platforms, are similar features available, and, if so, how best to determine if two seemingly different names are in fact the same file?

This question was also asked in Seekers of Perl Wisdom as Portable way to determine if two names refer to the same file?. The discussion there may also be of interest.

Answer: How do I portably determine if two filenames refer to the same file?
contributed by jcb

For POSIX systems, the first two values in the list returned by Perl's stat builtin provide a solution. These are the "device" and "inode" numbers for the file and, taken as a pair, uniquely identify a file.

# return true if both names are for the same file sub check_same_file_under_posix { my ($file_a, $file_b) = @_; my ($dev_a, $ino_a, @other_a) = stat($file_a); my ($dev_b, $ino_b, @other_b) = stat($file_b); if (($dev_a == $dev_b) && ($ino_a == $ino_b)) { return 1 } else { return 0 } }

Please (register and) log in if you wish to add an answer

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others musing on the Monastery: (1)
    As of 2021-02-25 06:03 GMT
    Find Nodes?
      Voting Booth?

      No recent polls found