Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

No need to call FindClose after FindNextFile failed?!

29 views
Skip to first unread message

programmer33

unread,
Oct 29, 2004, 1:20:32 PM10/29/04
to
Hi,

look at this piece of source from MSDN:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/listing_the_files_in_a_directory.asp

They don't call FindClose if FindNextFile really failed (GetLastError()
!= ERROR_NO_MORE_FILES). Is that okay or is this a bug?

Bye

Elias Fotinis

unread,
Oct 31, 2004, 3:50:34 PM10/31/04
to
programmer33 wrote:
> http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/listing_the_files_in_a_directory.asp
>
> They don't call FindClose if FindNextFile really failed
> (GetLastError() != ERROR_NO_MORE_FILES). Is that okay or is this a
> bug?

This is probably wrong code. You should always call FindClose for a
valid handle, no matter how the loop with FindNextFile ends:

HANDLE f = FindFirstFile(...);
if (f != INVALID_HANDLE_VALUE)
{
// FindNextFile loop
//...

FindClose(f);
}

Lucian Wischik

unread,
Nov 1, 2004, 6:45:47 PM11/1/04
to
"Elias Fotinis" <efoti...@SPAMpat.forthnet.gr> wrote:
>HANDLE f = FindFirstFile(...);
>if (f != INVALID_HANDLE_VALUE)
>{ // FindNextFile loop ...
> FindClose(f);
>}

I've long wondered what the neatest idiom is for FindFile. I've ended
up with this:

HANDLE hf=FindFirstFile(...);
for (BOOL b=(hf!=INVALID_FILE_HANDLE); b; b=FindNextFile(hf))
{ ...
}
if (hf!=INVALID_FILE_HANDLE) FindClose(hf);

This way, it's compact, readable, non-nested, and 'continue' and
'break' statements within the loop are robust (in the sense that they
don't need accompanying FindNext/FindClose).

--
Lucian

Alex Blekhman

unread,
Nov 2, 2004, 2:41:57 AM11/2/04
to
Lucian Wischik wrote:
> I've long wondered what the neatest idiom is for FindFile.

Alternatively you can wrap the logic in C++ class; similar to MFC's
CFindFile. Then it will be exception resistant, too.


0 new messages