Yes, fgets() is safe and clean for the purpose (getting information from the user). Just keep in mind that the trailing '\n' is placed into the destination buffer when there is room enough. If the input is greater than the given size, the trailing '\n' is missing.
Originally Posted by Salem
The ususal trick to manage it is :
Of course, you are not going to add all that stuff each time you use fgets(). This is the reason why it is recommended to build your own reusable 'getline' (or whatever) function, based on this code.
fgets (buf, ...);
/* search the '\n' */
char *p = strchr (buf, '\n');
if (p != NULL)
/* found : kill it. */
*p = 0;
/* not found : error handling */
/* one option is to flush the stream
* (ignore the extra characters)
while ((c = fgetc (stream)) != '\n' && c != EOF)
that returns buf (ok) or NULL (error)
char *getline (char *buf, size_t size, FILE *stream);
that returns 0 (ok) or different meaningful error values...
int getline (char *buf, size_t size, FILE *stream);