Creating a class around 'FindFirstFile()'

Hi, I've been using a function to search directories for files. Never had a problem with it until I tried to create a class around it. I've made a console app to test it out. The handle to the file always returns INVALID_HANDLE_VALUE. What could be wrong ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int DIRSEARCH::SearchDirectory(std::vector<std::string> &refvecFiles,
                    const std::string        &refcstrRootDirectory,
                    const std::string        &refcstrExtension,
                    bool                     bSearchSubdirectories)
{

	std::string     strFilePath;             // Filepath
	std::string     strPattern;              // Pattern
	std::string     strExtension;            // Extension
	HANDLE          hFile;                   // Handle to file
	WIN32_FIND_DATA FileInformation;         // File information
	
	strPattern = refcstrRootDirectory + "\\*.*";

	std::string strFileName;

	hFile = FindFirstFile((LPCWSTR)strPattern.c_str(), &FileInformation);
	if(hFile != INVALID_HANDLE_VALUE)    //always fails here :(
	{
		do
		{
                      //doing stuff...
                } while(FindNextFile(hFile, &FileInformation) == TRUE);             
                FindClose(hFile);
	}
	printf("GetLastError: %d", GetLastError());
	return 0;
}


Any ideas ? Thanks ~~~
You have a holy mess of ANSI and UNICODE. Best rule of thumb you'll ever get: If you have to typecast, you're probably doing something wrong. And this is the case for you. If you had to typecast c_str(), that should have given you the hint.

1. std::string is a class based on the char data type.
2. FindFirstFile() is a function that works with TCHAR's, not chars.

So basically you are trying to feed a UNICODE-agnostic function (FindFirstFile) an ANSI C string being forcefully cast as a wide C string.

My recommendation: Work with UNICODE explicitly. Use WIN32_FIND_DATAW with FindFirstFileW() and change all std::string's to std::wstring's. Remember to L-prepend all string and character literals.
Last edited on
Thanks webJose your answer is great !

I've changed all of my strings to wstring. The func then went into the 'do' loop but never found a match... After some more debugging I found another blunder with how I was extracting the extension from the file names. Honestly I'm not sure how it was working in the first place. It's fixed now though and working as smooth as I need it for now :)

Clearly, I was just lucky that this originally worked at all. That's what I get for copying code without really going through it :p
Topic archived. No new replies allowed.