INTRODUCTION:
I am reading from text file with ReadFile. Buffer passed to ReadFile is sent to standard output with cout. Standard output is redirected to a text file.
PROBLEM:
Although my code "works", no data is lost, resulting file is larger than the original one.
When opened in notepad, everything seems fine, but when opened in Notepad++ I can clearly see extra lines added. These lines are new lines (\n).
MVCE that reproduces this behavior is submitted below.
#include <iostream>
#include <windows.h>
int main()
{
HANDLE hFile = ::CreateFile("C:\\123.txt",
GENERIC_READ,
FILE_SHARE_READ |
FILE_SHARE_WRITE |
FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (INVALID_HANDLE_VALUE == hFile)
return ::GetLastError();
char buffer[256];
DWORD bytesRead = 1, bytesWritten = 0;
HANDLE hStandardOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
if (INVALID_HANDLE_VALUE == hStandardOutput)
{
std::cout << "GetStdHandle error code = " << ::GetLastError() << std::endl;
::CloseHandle(hFile);
return ::GetLastError();
}
while(bytesRead)
{
::memset(buffer, '\0', sizeof(buffer));
if (!::ReadFile(hFile,
buffer,
sizeof(buffer) - 1, &bytesRead, NULL))
{
std::cout << "ReadFile error code = " << ::GetLastError() << std::endl;
break;
}
std::cout << buffer; }
::CloseHandle(hFile);
return 0;
}
QUESTION:
What is causing above described behavior? How to fix it?
What I have tried:
As I type this post I am Googling aimlessly, hoping for some clue to show up.
I suspect that the problem lies when outputting \n, it seems that Windows inserts \r as well, but I am not sure.