What should I use, instead of gets?

Iter Ator picture Iter Ator · Apr 29, 2014 · Viewed 7.9k times · Source

There is a finished project, which is not mine. It works well, but if I build, I get a warning:

the 'gets' function is dangerous and should not be used.

I have to now fix the project, but I have no idea, how to replace this function

Answer

Clifford picture Clifford · Apr 29, 2014

Use fgets() on the stdin stream.

Note that unlike gets(), fgets() will not remove the newline character at the end of the input if it will fit in the buffer.

If stripping the newline and handling behaviour when input exceeds the provided buffer you might write a wrapper such as:

char* read_line( char* buffer, size_t buffer_len )
{
    char* line = fgets( buffer, buffer_len, stdin ) ;
    char* nl = strchr( buffer, '\n' ) ;
    if( nl != 0 )
    {
        // Replace newline character with nul
        *nl = 0 ;
    } 
    else
    {
        // If buffer was shorter than the line - read and discard rest of line.
        while( getchar() != '\n' ) { \* do nothing*\ }
    }

    return line ;
}