Your question is inconsistent, you ask about leading whitespace but your example shows trailing whitespace. If you mean trailing whitespace, you could do it this way:
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 25
int main() {
char string[BUFFER_SIZE];
memset(string, ' ', BUFFER_SIZE - 1); // initialize with spaces
string[BUFFER_SIZE - 1] = '\0'; // terminate properly
if (fgets(string, BUFFER_SIZE, stdin) != NULL) {
size_t length = strlen(string);
string[length - 1] = ' '; // replace the newline \n
if (length < BUFFER_SIZE - 1) {
string[length] = ' '; // replace extra '\0' as needed
}
printf("'%s'\n", string); // extra single quotes to visualize length
}
return 0;
}
USAGE
> ./a.out
this is a test
'this is a test '
>
The single quote were only added so you could actually see the spaces were preserved. The approach of @BLUEPIXY makes perfect sense except that it appends new whitespace to the input where you specifically asked about preserving existing whitespace.
If instead you want to preserve leading whitespace, that can probably be done as well.