title: plain C: opening a directory with fopen()
body: <p>I have a program which opens a file and checks its length.</p>
  
  <pre><code>FILE* fd = fopen(argv[1], "rb");
  fseek(fd, 0, SEEK_END);
  size_t flen = ftell(fd);
  if (flen == ((size_t)-1)) {
      printf("%s is a directory.\n", argv[1]);
      fclose(fd);
      exit(1);
  }
  </code></pre>
  
  <p>Now, at least under Linux, <code>fopen()</code> returns a valid file descriptor when opening a directory. This results in the seek operation returning <code>-1</code> (or, as <code>size_t</code> is unsigned, <code>0xFFFFFFFFFFFFFFFF</code>=2<sup>64</sup>-1 on a 64-bit system).</p>
  
  <p>Unfortunately, the condition in the above code (<code>flen == ((size_t)-1)</code>) does not catch that case, neither does <code>flen == 0xFFFFFFFF</code> (EDIT: should be <code>0xFFFFFFFFFFFFFFFF</code>). <code>printf()</code>-Commands with <code>%x</code> ord <code>%d</code> as format string show that both sides of the comparison should have the same value.</p>
  
  <p>Why does the comparison operator behave in such a strange way, even when both sides are of the same type (<code>size_t</code>)? I am using gcc 4.8.1 as compiler.</p>