First, after all the text, you should add '\0'at the end of the line
it should look like buffer[ index ] = 0;because you have to rewrite your character \nthat you added too.
Of course, there are other things you should check, but they are not your main concern.