c++ – WIN32_FIND_DATA Problems – cFileName – Education Career Blog

i have a problem with my code 😉

hFind = FindFirstFileEx( szPath, FindExInfoMaxInfoLevel, &FindData, FindExSearchNameMatch, NULL , 0);

strncpy_s( pszFileName, 280, FindData.cFileName, strlen(FindData.cFileName));

everything seems fine but when i copy the executable to another computer (windows 2003) i get
But for pszFileName i get really strange output

,

Specifying FindExInfoMaxInfoLevel is incorrect. The MSDN Library says:

FindExInfoMaxInfoLevel

This value is used for validation. Supported values are less than this value.

In addition, from your usage of FindFirstFileEx, I cannot see why you do not use the simpler FindFirstFile function.

,

There’s not enough code to diagnose the problem, especially without any evidence of error checking. However, there is something really smelly in what you posted. Your call to strncpy_s() says that pszFileName is a pointer to an array with 280 elements. Where did that number come from? Is it just a guess? It can never be more than 260 on Windows, why is it more? I suspect that when you make this a real number, like an argument passed to your function, instead of a guess that you’ll fix the problem as well.

,

You shuold not use the output fields in FindData without first checking that hFind is valid. From the MSDN docs:

If the function fails or fails to
locate files from the search string in
the lpFileName parameter, the return
value is INVALID_HANDLE_VALUE and the
contents of lpFindFileData are
indeterminate.

Thus you should have (after fixing other problems in your API call described in the answers here):

hFind = FindFirstFileEx( szPath, /* replace FindExInfoMaxInfoLevel here */, 
    &FindData, FindExSearchNameMatch, NULL , 0);
if (hFind != INVALID_HANDLE_VALUE)
{
  strncpy_s( pszFileName, 280, FindData.cFileName, strlen(FindData.cFileName));
}

Leave a Comment