Reputation: 539
New to C programming.
The following section of code attempts to read a tab-separated list of MD5 (32 chars) and corresponding description (up to 128 chars) from a text file (utf-8), but is causing the application to crash:
HANDLE hFile = CreateFileW(good_path, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return FALSE;
}
LPWSTR md5 = malloc(sizeof(wchar_t) * 32);
LPWSTR desc = malloc(sizeof(wchar_t) * 128);
int i;
while((i = fwscanf(hFile, L"%ls %ls", md5, desc)) != EOF)
{
if (i == 2) // OK
{
}
else // Something went wrong
{
}
}
CloseHandle(hFile);
return TRUE;
Few questions:
Update 1
I've taken this code and made it into a standalone exe (rather than a DLL). Still crashes.
Update 2
Updated to fwscanf as per Chris's comment. Still crashes. If I comment out the while...fwscanf...
line it exits properly.
Upvotes: 1
Views: 173
Reputation: 4430
CreateFileW()
returns a Windows handle, which is sort of like a file number but different somehow. fwscanf()
expects a FILE*
not a Windows handle; to get a FILE*
open your file with fopen()
or _wfopen()
.
Upvotes: 3
Reputation: 488
%s stores a nul-terminated string under the address your provide. To store n significant characters without buffer overflow, you need to provide an address of n+1 long buffer.
Upvotes: 0