Is it correct that in C programming when we pass the parameters pointer_to_string
, sizeof_string
and the stream
for the fgets()
function, we do not have to write back the return of the function to the pointer_to_array
that was defined earlier/given as the parameter for fgets()
.
Why would that be a mistake?
char string_ofsize_ten[10];
string_ofsize_ten = fgets(string_ofsize_ten, 10, stdin);
Array expressions like array_ofsize_ten
cannot be the target of an assignment; the language simply doesn't allow it. fgets
will write to the array as part of its operation, so you don't need to assign the result back to the original array.
The return value is mainly used to test if the operation succeeded; fgets
will return NULL
if it sees an EOF or error on the input stream before any characters:
if ( fgets( target, sizeof target, stream ) ) // implicit test against NULL
{
// process target
}
else if ( feof( stream ) )
{
// handle EOF
}
else
{
// handle I/O error
}
You could also pass that return value as an argument to another function that expects a char *
:
printf( "%s\n", fgets( target, sizeof target, stream ) );
although this will blow up if fgets
returns NULL
, so it's not used that much.