Link to home
Start Free TrialLog in
Avatar of junkyboy
junkyboy

asked on

FindFirstFile and FindNextFile usage

I'm using MS Vis C++ 6.0 on an NT machine.  I need some help in using FindFirstFile and FindNextFile.  If someone could give me 2 simple codes, it would be great.  1) I need a code that would output the list of files (and directories if possible) to screen.  2) I need a code that would output the list of files (and directories if possible) to an array.

Thanks in advance!
ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nietod
nietod

The array is a little more difficult, how do you know haw big to make it?  You can count the files and then allocate the array dynamcially, but a beter idea would be to use an array class, like vector<>.  At that point it is probably a good idea to use a string class to store the name too, so I'll use a vector of strings, like

  vector<string> FileList;

  BOOL  Done;                     // Done searching for files?
   HANDLE  FndHnd = NULL;   // Handle to find data.
   WIN32_FIND_DATA FindDat;  // Info on file found.

   FndHnd = FindFirstFile("C:\\*.txt", &FindDat);
   Done = (FndHnd == NULL);       // Indicate we are done if nothing was found.

   while (!Done)
   {
      string FileName = FindDat.cFileName;

      FileList.push_back(FileName);
      Done = !FindNextFile(FndHnd, &FindDat);
   }
   if (FndHnd)            // If there was anything found, then
      FindClose(FndHnd); // Close the find handle

Let me know if you have any questions.
nietod ,this code is wrong:

Done = (FndHnd == NULL);      

should be

Done = (FndHnd == INVALID_HANDLE_VALUE);

Regards
Right!.  I made that misake before.  (That is from my EE notes).  I corrected my mistake when it was pointed out.  But the the correction was lost (apparently) when I lost my computer to a virus.  Thanks.  Correcting again.....
Avatar of junkyboy

ASKER

When I tried using the above code, Visual returns a "Access Violation" and I get strange characters instead of filenames.  This occurs after compiling/linking.
Sorry, I think I was doing something wrong in my code.  I got it all working.  Thank you for all your support, everyone! :)