MSalmo
MSalmo

Reputation: 372

fwrite outputs character string incorrectly

I am currently writing a C++ program to control some LEDs by sending strings via termios to an Arduino. Each line is ended by a newline character. I have written a test program that would output to the terminal, but there are issues with the output of the following code snippet:

char* ledAddr = (char*)malloc(3);
char* rVal = (char*)malloc(3);
char* gVal = (char*)malloc(3);
char* bVal = (char*)malloc(3);
...
fread(ledAddr, 3, 1, stdin);
fread(rVal, 3, 1, stdin);
fread(gVal, 3, 1, stdin);
fread(bVal, 3, 1, stdin);
...
char* outputString = malloc(17);

outputString[0] = 't';
strncpy(outputString+1, rVal, 3);
outputString[4] = ',';
strncpy(outputString+5, gVal, 3);
outputString[8] = ',';
strncpy(outputString+9, bVal, 3);
outputString[12] = ',';
strncpy(outputString+13, ledAddr, 3);
outputString[16] = '\n'

fwrite(outputString, 17, 1, stdout);

This is my test input:

180
255
0
0

This is my expected output:

t255,0,0,180

And this is what I wind up with:

t
25,5
0,0,
184

Any help would be appreciated.

Upvotes: 0

Views: 190

Answers (1)

Dietmar Kühl
Dietmar Kühl

Reputation: 153792

Looks correct to me. You probably wanted to skip the newlines but fread() won't do that for you. If you wanted the FILE operations to read lines, you'd use fgets() rather than fread().

Upvotes: 2

Related Questions