When using fwrite to write to stdout I experience weird insertions.
I read from original.txt to a buffer, and then write the buffer both to file.txt and to stdout. I save the stdout to stdout.txt. All files are treated as binary files.
program.exe > stdout.txt
The file.txt becomes identical with original.txt.
stdout.txt has 3 extra bytes compared to original.txt, consisting of a inserted value 0x0D before every 0x0A.
What could be the reason for the insertions in stdout? Not sure I can trust stdout any more.
Testing is done in 2 steps:
program.exe > stdout.txt
Change true to false on line 16 and run:
program.exe
Expected output - occourances of insertions (offset, inserted value, the original value):
6ec : d, a
c68 : d, a
ecc : d, a
Code:
#include <cstdio>
#include <iostream>
int main()
{
// original.txt -> read_data
char read_data[0x1000];
FILE * original_p = fopen("original.txt", "rb");
fread(read_data, 1, 0x1000, original_p);
fclose(original_p);
//True : write files.
//False : compare files.
if (true)
{
// read_data -> file.txt
FILE * file_p = fopen("file.txt", "wb");
fwrite(&read_data[0], 1, 0x1000, file_p);
fclose(file_p);
// read_data -> stdout
fwrite(&read_data[0], 1, 0x1000, stdout);
}
else
{
// stdout.txt -> stdout_data
char stdout_data[0x1003];
FILE * stdout_file = fopen("stdout.txt", "rb");
fread(stdout_data, 1, 0x1003, stdout_file);
fclose(stdout_file);
// Compares read_data and stdout_data:
int extra_offset = 0; // Compensates for insertions in stdout_data.
for (int n = 0; n < 0x1000;n++)
{
if (stdout_data[n + extra_offset] != read_data[n])
{
// Prints offset : stdout_data[n + extra_offset], read_data[n]
std::cout << std::hex <<
n << " : " <<
(((unsigned int) stdout_data[n + extra_offset]) & 0xFF) << ", " <<
(((unsigned int) read_data[n]) & 0xFF) << "\n";
extra_offset += 1;
}
}
}
return 0;
}