Search code examples
cscanfstdio

Reading a line using scanf() not good?


scanf(" %[^\n]",line);

A friend of mine suggested that using fgets() to read a line as input would be a much better idea than using scanf() as in the statement above. Is he justified?


Solution

  • char * fgets ( char * str, int num, FILE * stream ); is safe to use because it avoid buffer overflow problem, it scans only num-1 number of char.

    Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.

    here second argument num is Maximum number of characters to be copied into str (including the terminating null-character).

    For example suppose in your code a string array capacity is just 5 chars long as below.

     char str[5];
     fgets (str, 5, fp);  //5 =you have provision to avoid buffer overrun 
    

    Using above code, if input from fp is longer then 4 chars, fgets() will read just first 4 chars then appends \0 (, and discard other extra input chars, just stores five char in str[]).

    Whereas scanf(" %[^\n]",str); will read until \n not found and if input string is longer then 4 chars scanf() will cause of buffer overflow (as scanf will try to access memory beyond max index 4 in str[]).