Trying to create a handle from existing file (test.txt), read the data to buffer and printing the buffer using printf.
Everything apparently works fine - There is no errors and the number of bytes read by ReadFile is correct. But when I printing the buffer with printf, some garbage prints after the data from the txt file to the screen:
The code is:
#include <windows.h>
#include <stdio.h>
WCHAR input_file[9] = L"test.txt";
LPCWSTR p_input_file = input_file;
#define BUFFER_SIZE 24
int main()
{
HANDLE hFile = NULL;
CHAR inBuffer[BUFFER_SIZE];
LPVOID pbuffer = inBuffer;
DWORD nNumberOfBytesToRead = BUFFER_SIZE;
DWORD nNumberOfBytesRead;
hFile = CreateFile(input_file,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
BOOL reading_result = ReadFile(hFile,
pbuffer,
nNumberOfBytesToRead,
&nNumberOfBytesRead,
NULL);
int error_code_value = GetLastError();
if (error_code_value == 0)
{
printf("Work properly. The text is: %s \n", inBuffer);
}
else if (error_code_value == ERROR_INVALID_HANDLE)
{
printf("Handle is loaded in invalid way.\n");
}
else
{
printf("Worked wrong. error code: %d. \n", GetLastError());
}
CloseHandle(hFile);
}