views:

298

answers:

2

Output:

The first file found is LOG_09.TXT
Next file name is LOG_10.TXT
Next file name is LOG_11.TXT
Next fi                         (cut off word "file"?)

Function:

//Find last modified log file
    hFind = FindFirstFile("..\\..\\LOGS\\LOG*.TXT", &FindFileData);
    if (hFind == INVALID_HANDLE_VALUE) 
    {
      printf ("FindFirstFile failed (%d)\n", GetLastError());
      return;
    } 
    else 
    {
      printf("The first file found is %s<br>",FindFileData.cFileName);

      //List all the other files in the directory.
      while (FindNextFile(hFind, &FindFileData) != 0) 
      {
         printf ("Next file name is %s<br>", FindFileData.cFileName); //NOT DISPLAYING ALL NAMES CONSISTENTLY??

      }

      dwError = GetLastError();
      FindClose(hFind);

      if (dwError != ERROR_NO_MORE_FILES) 
      {
         printf ("FindNextFile error. Error is %u.\n", dwError);
         return (-1);
      }

    }

The word "file" is actually cut short in my printf. Sometimes it displays all the file names sometimes it displays a few, sometimes it doesn't even finish the printf quoted line, like shown above. What is causing this and am I being mislead by the printf functionality? In the debugger it looks like everything is OK, but I want to be certain and understand this. For example, I don't have a null char after i in file right? Why is it being cut off here? Thanks.

EDIT: Incorrect - Single threaded application library. (Was multithreaded before, sorry)

printing to a file gives the complete list of files while printf concurrently is "unstable". Not sure I understand why....

+1  A: 

Since your app is multithreaded, the printf may get cut short half way through, by another thread which then gets control, try this:

  1. After all printf() calls, use fflush(stdout);, to make sure that the buffer is flushed.
  2. If that doesn't fix it you can protect the stdout resource with a named mutex, or a critical section. Basically wrap all printf + fflush calls with a Wait, followed by a Signal on the named mutex.

(Not sure if step 2 will be necessary).

DeusAduro
it's worth noting that stdout is not line buffered on windows. that means the likelihood of interleaved output to stdout is much greater. flushing would be good practice, and a critical section would be the simplest choice and best fit for this problem.
Matt Joiner
+1  A: 

Since you say your program is multi-threaded, I would guess that the thread this function is executing in is being killed early. This wouldn't happen when running under the debugger. You need some thread synchronization to ensure this thread is allowed to complete.

Rob K
i believe it could happen, it's just less likely
Matt Joiner