Question

Consider the following code

FILE * pOutFile;

unsigned char uid;

pOutFile = fopen("OutFile.bin","w") ;  // open a file to write

uid = 0x0A;

fprintf (pOutFile,"%c",uid);          // Trying to print 0x0A in to the file

But the print I get in the file is

0x0D 0x0A

Where is this 0x0D coming from? Am I missing something? What consideration must I take to prevent this.

Corrected: uidl was a typo.

Was it helpful?

Solution

Windows text files want new lines to be represented by two consecutive chars: 0x0D and 0x0A.

In C, a new line is represented by a single char: 0x0A.

Thus, on Windows, in C, you have two ways to open a file: text mode or binary mode.

In binary mode, when you write a LineFeed (0x0A) char, a single byte (0x0A) is append to the file.

In text mode, whenever you write a LineFeed (0x0A) char, two bytes (0x0D and 0x0A) are append to the file.

The solution is to open the file in binary mode, using "wb".

OTHER TIPS

Because you have opened the file in "w" mode it is in TEXT mode, which means \n's (aka 0x0a) are translated into \r\n (carriage return and line feed). If you only want 0x0a written to the file open it in binary mode ("wb").

Actually, none of those are the issue...

FILE * pOutFile;
unsigned char uid;
pOutFile = fopen("OutFile.bin","wb") ;  // open a file to write (in binary, <b>not</b> text mode)
uid = 0x0A; //changed from uidl = 0x0A (which didnt set uid)
fprintf (pOutFile, "%c", uid);          // Trying to print 0x0A in to the file

What I changed, was you were setting uidl and NOT uid, which you printed.

You could always do the following:

fprintf(pOutFile, "%c", 0x0A); or
fprintf(pOutFile, "%c", '\n'); or
fprintf(pOutFile, "\n");

if you wanted (the last option is probably your best.

I also opened your file in wb mode.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top