I have written the following function to get user input from stdin and clear the buffer.
*readRestLine is a function provided by my lecturer to clear the buffer.Code:char* getUserInput() {
static char buffer[BUFFER_SIZE + 1];
if (fgets(buffer, sizeof buffer, stdin) != NULL) {
if ((strlen(buffer)) == BUFFER_SIZE &&
buffer[BUFFER_SIZE - 1] != '\n')
readRestOfLine();
}
return buffer;
}
This code is working perfectly for me but I am wondering if I need to (or should) have an else statement for when fgets returns null.
Is it possible for fgets to return null when reading from stdin? If not why is the test for null required?
I new to C as you can tell and I am just trying to get my head around what is happening here and learn the best practice for these situations
thanks in advance
Michael