Okay, I think I know the problem, but I don't know how to solve it. I want to write a binary file with raw bytes. Windows appears to interpret 10 as ASCII 10 and it does its thing where it interprets 10 as '\n' and decides to change that to "\r\n" or something. But these are bytes, they aren't characters, and they need to be manipulated mathematically later, so I want to write a single 0x0A byte to the file, not two bytes (0x0D 0x0A). Basically I want the program below to write 20 bytes and I want them to all be 10, but it's writing 40 bytes and they alternate between 0xA and 0xD (see screenshot). However, the assert statement on line 18 doesn't fail, so the fwrite function returns 20.

Any ideas?

#include <stdio.h>
#include <assert.h>

int main ()
	unsigned char bytes[20];
	FILE* binFile;
	int numBytesWritten;
	int i;

	for (i = 0; i < 20; i++)
		bytes[i] = 10;

	binFile = fopen ("BinaryFile.bin", "w");
	numBytesWritten = fwrite (bytes, 1, 20, binFile);
	assert (numBytesWritten == 20);
	fclose (binFile);
	return 0;

Can't seem to upload the screenshot.

Edited by VernonDozier: n/a

Attachments BinaryFile.jpg 169.15 KB
7 Years
Discussion Span
Last Post by VernonDozier
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.