title: Waiting until a file is available for reading with Win32
body: <p>I'm watching a directory by calling <code>ReadDirectoryChangesW</code> synchronously. When a new file is available, I try to access it immediately with <code>CreateFile</code> with <code>GENERIC_READ</code> and <code>FILE_SHARE_READ</code>, but this gives me <code>ERROR_SHARING_VIOLATION</code>. The process that put the file in the watched directory does not finish writing by the time I try to read it.</p>
  
  <p>Is there any way to reliably wait until the file is available for reading? I can put the method into a loop like the one below, but I'm hoping there's a better way.</p>
  
  <pre><code>while ((hFile = CreateFile (path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE)
  {
      if (GetLastError() == ERROR_SHARING_VIOLATION)
          Sleep (500);
      else
          break; // some other error occurred
  }
  
  if (hFile == INVALID_HANDLE_VALUE)
  {
      // deal with other error
      return 0;
  }
  
  ReadFile (...);
  </code></pre>