Reputation: 147
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
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 isINVALID_HANDLE_VALUE
and the contents oflpFindFileData
are indeterminate. To get extended error information, call theGetLastError
function.
and INVALID_HANDLE_VALUE
is #define
d 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
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