FindFirstFile and FindNextFile question

2019-08-01 06:42发布

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....

2条回答
Anthone
2楼-- · 2019-08-01 07:20

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).

查看更多
迷人小祖宗
3楼-- · 2019-08-01 07:37

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.

查看更多
登录 后发表回答