title: Iterate through a text file in C++ using for_each and istream_iterator to find file names
body: <p>Working on a C++ HW project. We were given code to read all .dat files in a directory into a single .txt file, which we then need to extract values from, in no particular order. The code we were given was:</p>
  
  <pre><code>#if defined(_WIN32)
  #define listcmd "dir \b *.dat &gt; datfiles.txt 2&gt;nul"
  #endif
  </code></pre>
  
  <p>This gives me a text file with a lot more information than just the .dat file names, though... volume information, directory paths, file data, etc.</p>
  
  <p>We then do the following to read the file, but I do not understand how this works:</p>
  
  <pre><code>system(listcmd);
  ifstream datfiles("datfiles.txt");
  for_each(istream_iterator&lt;string&gt;(datfiles), istream_iterator&lt;string&gt;(), analyze);
  datfiles.close();
  </code></pre>
  
  <p>I have been looking over the istream_iterator and for_each pages at cplusplus.com, but could use some clarification. What exactly is this for_each statement doing?</p>
  
  <p>Am I correct in thinking that it is doing the following:</p>
  
  <ul>
  <li>reading one string at a time from the istream (stopping on white space)</li>
  <li>passing that string to the analyze function (to perform whatever processing... attempting to open the file in my case and reading in values)</li>
  <li>once control returns, continue doing this until end of file reached or stream fails</li>
  </ul>