The original K&R defined fgets()
on p.155 with an int
argument. The code presented in the book would have worked
with an unsigned int
as well (it uses a >0
, but the loop is written so to never go below zero).
size_t
got introduced later, in C89 (ANSI C), as the type of sizeof()
. As this feature was specifically introduced for harmonizing memory allocation, memory
management functions and string functions were updated accordingly. But file I/O wasn't: the only file functions that used size_t
in C89 are those new ones
introduced by C89 and did not exist in K&R such as for example fread()
/fwrite()
. Yes, K&R didn't have these functions
and relied for bloc operations only on (non portable) unix read/write functions using file descriptors.
It shall be noted that the POSIX standard, which has harmonized the unix functions, was developed in parallel to
the ANSI C standard and issued late 1988. This standard has harmonized many unix functions to use size_t
so that read()
/write()
nowadays
are defined with size_t
. But for the C standard library functions such as fgets()
, POSIX gives precedence to the C standard
(wording of the current version of the standard):
The functionality described on this reference page is aligned with the ISO C standard.
Any conflict between the requirements described here and the ISO C standard is unintentional.
So in POSIX also, ironically, fgets()
still inherited from its historical K&R int
.
Edit: additional reading
stdio.h: This header defines and prototypes most of the functions listed in Chapter 7 of K&R. Few, if any, changes were made in the
definitions found in K&R but several new functions have been added.