I am trying to read from a file using the Windows function ReadFile()
, but when I print the message it prints too many characters.
It doesn't matter if I read from an ANSII file or UNICODE file, I don't get the right characters.
Text in file is : "This is a text file".
Screen shot for the ANSII file:
Screen shot for the UNICODE file:
What Am I doing wrong?
#define BUFSIZE 4000
int _tmain(int argc, TCHAR *argv[])
{
HANDLE hIn;
TCHAR buffer[BUFSIZE];
DWORD nIn = 0;
//create file
hIn = CreateFile(argv[1],
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
//check the handle
if (hIn == INVALID_HANDLE_VALUE)
{
printf("\nOpen file error\n");
}
//read from file
if (FALSE == ReadFile(hIn, buffer, BUFSIZE - 1, &nIn, NULL))
{
printf("Terminal failure: Unable to read from file.\n GetLastError=%08x\n", GetLastError());
CloseHandle(hIn);
return 0;
}
if (nIn > 0 && nIn <= BUFSIZE - 1)
{
buffer[nIn] = TEXT('\0'); // NULL character
_tprintf(TEXT("Data read from %s (%d bytes): \n"), argv[1], nIn);
}
else if (nIn == 0)
{
_tprintf(TEXT("No data read from file %s\n"), argv[1]);
}
else
{
printf("\n ** Unexpected value for nIn ** \n");
}
printf("1:%s\n", buffer);
_tprintf(TEXT("\n2:%s"), buffer);
return 0;
}