Microsoft Learn

FindFirstFileW

HANDLE FindFirstFileW( LPCWSTR lpFileName, LPWIN32_FIND_DATAW lpFindFileData );

The FindFirstFileW function begins the process of a generic-purpose file searching. It has been superseded by FindFirstFileNameW, which retrieves the names of files that have the specified attributes and whose names match the specified string. The FindFirstFileW function is still supported for backward compatibility.

Parameters

Parameter Description
lpFileName

A pointer to a null-terminated string that specifies a valid directory or drive, and also a file name. This parameter can be a specific file name, a wildcard specification (for example, "*.doc"), or a combination of directory and wildcard specification.

This parameter can be NULL. If the parameter is NULL, the function fails with ERROR_INVALID_PARAMETER.

lpFindFileData

A pointer to a WIN32_FIND_DATAW structure that receives information about a found file or directory.

Return Value

If the function succeeds, the return value is a search handle used by the subsequent calls to the FindNextFileW function and must be closed with the FindClose function. If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.

Remarks

Security Considerations

Do not pass a user-supplied value for lpFileName directly to the FindFirstFileW function, as this could lead to an insecure application. Instead, use a correctly formed path.

If the path is an empty string or NULL, FindFirstFileW will fail with ERROR_INVALID_PARAMETER.

Example Usage

This example searches for all files ending with the .txt extension in the current directory.

#include <windows.h>

int main() {
    WIN32_FIND_DATAW findFileData;
    HANDLE hFind = INVALID_HANDLE_VALUE;
    
    // Start finding all files in the current directory with .txt extension     hFind = FindFirstFileW(L"*.txt", &findFileData);
    
    if (hFind == INVALID_HANDLE_VALUE) {
        printf("Error finding files.\n");
        return 1;
    }
    
    // Loop through all files found     do {
        wprintf(L"Found file: %s (%d bytes)\n",
                    findFileData.cFileName, (int)findFileData.nFileSizeLow);
    } while (FindNextFileW(hFind, &findFileData) != 0);
    
    FindClose(hFind);
    return 0;
}

Requirements

Attribute Value
Minimum supported client Windows 2000 Professional
Minimum supported server Windows 2000 Server
Header fileapi.h (include windows.h)
Library Use Kernel32.lib
DLL Kernel32.dll
Unicode and ANSI names
  • FindFirstFileW (Unicode)
  • FindFirstFileA (ANSI)
  • FindFirstFile

See Also