Victor
Victor

Reputation: 147

c++, output of FindFirstFile()

I wrote the program of finding file using FindFirstFile(...) function. But when I try to print the output of this function, there is a several strings of unknown characters printed in console windows. I read some posts, there was written to try using wcout instead of cout. I try it, but it doesn't help. I think, that the problem is in difference between ANSI and UNICODE encodings. Can somebody help me? I will be very thankful for any help!

Here is my code:

#include "FindFile.h"
#include <iostream>
using namespace std;

void FindFileCl::Execute(Input * input, Response * response )
{
    WIN32_FIND_DATAA FindFileData;

    HANDLE h = FindFirstFileA((input->FileName).c_str(),    // name of the file

        &FindFileData);
    if (h)
    {   



        cout << "Search Results:\n";

        cout<<(FindFileData.cFileName);


        CloseHandle(h);
    }
    else
    {
        cerr << "File is NOT found:" << GetLastError() << "\n";
    }




} 

Upvotes: 0

Views: 885

Answers (2)

hmjd
hmjd

Reputation: 121961

If FindFirstFile() fails it returns INVALID_HANDLE_VALUE, not NULL:

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. To get extended error information, call the GetLastError function.

and INVALID_HANDLE_VALUE is #defined as -1 (following macro located in WinBase.h):

#define INVALID_HANDLE_VALUE ((HANDLE)(LONG_PTR)-1)

Meaning the if (h) will be entered in either success or failure. In the event of failure, cFileName will not be modified resulting in junk being printed as it is not initialized. Change the if condition to explicitly check for INVALID_HANDLE_VALUE:

if (h != INVALID_HANDLE_VALUE)
{
}

Upvotes: 1

Medinoc
Medinoc

Reputation: 6608

One of the "least bad" ways would be to convert the Unicode name to the Console's encoding.

For this, I suggest compiling in Unicode (There's a project option for that in Visual Studio >=8; otherwise you have to define both UNICODE and _UNICODE manually), using the TCHAR version of FindFirstFile(), and then using CharToOem() or CharToOemBuff() (neither is perfect). -- Or alternately, use the W version followed by WideCharToMultiByte(CP_OEMCP).

Upvotes: 0

Related Questions