title: How-to open and close files in a loop
body: <p>I have a <code>while</code> loop that opens (and closes) files in each loop. After some loops I end up in the "Too many open files" problem – but I call <code>close</code> each time after reading the file's content. Could anyone assist me with this?</p>
  
  <pre><code>for (;;)
  {
      dir = opendir( "/proc");
  
      while ( (entry = readdir( dir)) != NULL)
      {
          pid = atoi( entry-&gt;d_name);
  
          // Only processes with a "number" are of interest
          if ( pid == 0)
              continue;
  
          sprintf( fname, "/proc/%d/cmdline", pid);
  
          fd = open( fname, O_RDONLY);
          read( fd, line, MAX_LINE);
  
          /* ... */
  
          close( fd);
      }
  }
  </code></pre>