Reading a line using scanf() not good?
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[]
).
C FAQ has some detailed explanation about scanf
's problem:
More generally,
scanf
is designed for relatively structured, formatted input (its name is in fact derived from "scan formatted"). If you pay attention, it will tell you whether it succeeded or failed, but it can tell you only approximately where it failed, and not at all how or why. You have very little opportunity to do any error recovery.
see here for detail.
fgets
will be better than this scanf
.
There may be following issues with scanf
as given in OP
1)buffer overflow as suggested by @Grijesh
2)possibly next scanf
after this won't work because the newline is left in the input stream.(if you miss a blank space)