title: Why is calling close() after fopen() not closing?
body: <p>I ran across the following code in one of our in-house dlls and I am trying to understand the behavior it was showing:  </p>
  
  <pre><code>long GetFD(long* fd, const char* fileName, const char* mode)
  {
      string fileMode;
  
      if (strlen(mode) == 0 || tolower(mode[0]) == 'w' || tolower(mode[0]) == 'o')
          fileMode = string("w");
      else if (tolower(mode[0]) == 'a')
          fileMode = string("a");
      else if (tolower(mode[0]) == 'r')
          fileMode = string("r");
      else
          return -1;
  
      FILE* ofp;
      ofp = fopen(fileName, fileMode.c_str());
      if (! ofp)
          return -1;
  
      *fd = (long)_fileno(ofp);
      if (*fd &lt; 0)
          return -1;
  
      return 0;
  }
  
  long CloseFD(long fd)
  {
      close((int)fd);
      return 0;
  }
  </code></pre>
  
  <p>After repeated calling of GetFD with the appropriate CloseFD, the whole dll would no longer be able to do any file IO.  I wrote a tester program and found that I could GetFD 509 times, but the 510th time would error.    </p>
  
  <p>Using Process Explorer, the number of Handles did not increase.  </p>
  
  <p>So it seems that the dll is reaching the limit for the number of open files; setting <code>_setmaxstdio(2048)</code> does increase the amount of times we can call GetFD. Obviously, the close() is working quite right.</p>
  
  <p>After a bit of searching, I replaced the <code>fopen()</code> call with:</p>
  
  <pre><code>long GetFD(long* fd, const char* fileName, const char* mode)
  {
      *fd = (long)open(fileName, 2);
      if (*fd &lt; 0)
        return -1; 
  
      return 0;
  }
  </code></pre>
  
  <p>Now, repeatedly calling GetFD/CloseFD works.</p>
  
  <p>What is going on here?  </p>