Threads, heap args, and directory enumeration
This chapter covers passing a structure to a worker thread with CreateThread, and enumerating files with FindFirstFileA / FindNextFileA / FindClose.
Passing a parameter to CreateThread
Allocate a struct (e.g. ARGS) on the heap, fill fields such as a search pattern, pass the pointer as lpParameter, then wait and clean up:
typedef struct _ARGS {
CHAR fileName[MAX_PATH];
} ARGS, *PARGS;
PARGS pArgs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(ARGS));
if (!pArgs)
return GetLastError();
memcpy(pArgs->fileName, "C:\\Users\\*", strlen("C:\\Users\\*") + 1);
HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)DirSearch, pArgs, 0, NULL);
if (!hThread) {
HeapFree(GetProcessHeap(), 0, pArgs);
return GetLastError();
}
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
HeapFree(GetProcessHeap(), 0, pArgs);
Warning
Casting
DirSearchtoLPTHREAD_START_ROUTINEonly works ifDirSearchuses the correct return type and calling convention (DWORD WINAPI ThreadProc(LPVOID)). Mismatches cause stack corruption.
Thread procedure: FindFirstFile loop
Inside DirSearch (or your name):
- If
lpParamis non-NULL, read((PARGS)lpParam)->fileName(or use a default pattern). FindFirstFileA→ checkINVALID_HANDLE_VALUE→GetLastErroron failure.do…while (FindNextFileA(...)).FileTimeToSystemTimefor display.- Combine
nFileSizeHigh/nFileSizeLowwithLARGE_INTEGERfor 64-bit size. - Skip
.and..; branch onFILE_ATTRIBUTE_DIRECTORY. FindClosebefore return.
Note
Pick a directory you are allowed to scan.
C:\*orC:\Users\*are teaching examples only.
Implement
- Define
ARGS(or use the template’s typedef), implementDirSearchin its own.cfile if your rubric splits modules. CreateThreadfrommain, wait, free heap.- Build, run, commit, and push.