Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between the fgetc() and fgets()?

Tags:

c

file

I am aware with the fact that fgetc() will read one character at a time from a file pointed by the FILE pointer which is used as argument.

fgets() will read the whole string upto the size specified in argument list but when end of line occurs fgetc() returns EOF while fgets() returns NULL.so why there are two confusing things to remember?

like image 661
OldSchool Avatar asked Dec 07 '22 03:12

OldSchool


1 Answers

The reason one returns EOF while the other returns NULL is the difference in return types of the two functions: one returns an int, while the other returns a char*.

Both functions need to return a "special" value when the end of the input is reached. By "special" I mean a value that cannot appear in the input legally. For pointers, the special value in most cases is NULL, so that is what fgets returns. However, you cannot use NULL to mark the end of the input from fgetc, because character code of zero can legally appear in the input. That is why EOF is used as the "special value" in I/O functions that return a single character.

like image 163
Sergey Kalinichenko Avatar answered Dec 08 '22 17:12

Sergey Kalinichenko