fwrite not working (LPC2129, newlib-lpc)

Hello all

I’ve spent a day trying to figure this out. I cannot seem to get fwrite to work. Everything else seems to run perfectly. Here’s what happens:

int a = 0;
printf("%d", a);

Prints 0, as expected

int a = 0;
fwrite(&a, sizeof(int), 1, stdout);

Prints 4 bytes of random garbage.

But:

int a = 0;
int b;
memcpy(&b, &a, sizeof(int));
printf("%d", b);

Prints 0 again, as expected. So pointers work. Same with malloc(), seems to work. But fwrite always fails. Why?

And finally,

int a = 0;
char* b = (char*)&a;
fputc(b[0], stdout);
fputc(b[1], stdout);
fputc(b[2], stdout);
fputc(b[3], stdout);
fflush(stdout);

Also prints garbage. So I guess the problem is in fputc? Or am I missing something obvious?

Edit: stupid me, the problem was a buggy serial terminal :slight_smile: As soon as I tried something different, the output was correct. I am not using gtkterm anymore! :evil:

But to me everything seems working correctly.

printf(“%d”,a); first converts the number a into its string representation, and then prints this out.

fwrite instead prints the number without converting it, so it outpus 0 in binary form, and since the arm is a 32bit machine, it prints 0x00 0x00 0x00 0x00 (four null characters)

If you want to print a number using fwrite try this:

char line[16];

sprintf(line,“%d\n”,a); //convert the number into its string representation

fwrite(a,strlen(line),sizeof(char),stdout);

but it is even better to use fprintf in this case:

fprintf(stdout,“%d\n”,a);