title: Check whether a file is a hard link
body: <p>How do you check whether a file is a <em><strong>hard</strong> link</em> in Go? <code>os.FileMode</code> only has a mode for symlinks, not hard links.</p>
  <p>I had an idea that unfortunately doesn't work:</p>
  <pre><code>package main
  
  func main() {
      filename := os.Args[1]
      var hardlink bool
      link, _ := os.Readlink(filename)
      fi, _ := os.Stat(filename)
      mode := string(fi.Mode().String()[0])
      if link != &quot;&quot; &amp;&amp; mode != &quot;L&quot; {
          hardlink = true
      }
      fmt.Printf(&quot;%v is hard link? %v\n&quot;, filename, hardlink)
  }
  </code></pre>
  <p>This^ doesn't work because <code>os.Readlink</code> reads only symlinks, not hard links.</p>
  <p>I found a <em>somewhat</em> related answer:<br />
  <a href="https://stackoverflow.com/questions/26854961/counting-hard-links-to-a-file-in-go">Counting hard links to a file in Go</a><br />
  But this answer shows how to find the <em>number</em> of hard links to a file, not <em>whether</em> a file itself is a hard link.</p>
  <p>I'm guessing that the <a href="https://golang.org/pkg/syscall/#Stat_t" rel="nofollow noreferrer">syscall</a> package used in that answer or, better yet, the <a href="https://godoc.org/golang.org/x/sys/unix#Stat_t" rel="nofollow noreferrer">sys</a> package has a way to test whether a file's a hard link. Does anyone know to do this? (I have trouble understanding those packages because they're so low-level.)</p>
  <h3>EDIT</h3>
  <p>I should add the reason why I'd like to check this. I'm trying to make a function to create a tar archive of a directory [using <code>filepath.Walk()</code>]. In this function, when I create the <code>*tar.Header</code> for a file, I set a value to <code>*tar.Header.Typeflag</code>.<br />
  For example, if <code>fi</code> is a file's <code>*os.FileInfo</code> variable and <code>hdr</code> is the <code>*tar.Header</code> variable for that file's place in a new tar archive, it looks like this:</p>
  <pre><code>if fi.Mode().IsDir() {
      hdr.Typeflag = tar.TypeDir
  }
  </code></pre>
  <p>In the <a href="https://golang.org/pkg/archive/tar/#pkg-constants" rel="nofollow noreferrer">tar</a> package, the modes for hard links and regular files are distinct, <code>TypeLink</code> and <code>TypeReg</code>, but this isn't the case in the <a href="https://golang.org/pkg/os/#FileMode" rel="nofollow noreferrer">os</a> package. So running this won't set the correct <code>Typeflag</code>:</p>
  <pre><code>hdr.Mode = int64(fi.Mode())
  </code></pre>