>And in other words I said if you would allow me to ask you why
>would you choose to return the length of the string, instead of
>returning a pointer to the string that has been worked on, or a NULL if not successful.
That's slightly different from how I interpreted your question, which strongly implied that I wrote the fgetline function (which I didn't).
However, to answer your question, here are some reasons for why I would choose to return the length of the string or a suitable "impossible" length:fgetline, like fgets, takes a pointer to the buffer as an argument, so returning a pointer to the buffer is nothing more than a convenience. In the case of fgets, conventional usage nearly always results in the return value being used strictly for a success/failure test. Because the value could be NULL, you can't safely do something like this:
fputs ( fgets ( buffer, sizeof buffer, stdin ), stdout );
As such, the majority of the convenience is lost and if a better return value can be found, it's a good argument fornot using a pointer to the buffer.
In just about every case, the length of the string is a useful entity. When you find yourself calling fgets and then shortly (or immediately) thereafter calling strlen, it makes a lot of sense for an fgets wrapper to return the result of strlen and save you the trouble.
Returning the length of the string also doesn't preclude the current conventional usage of fgetline. The exact same success/failure test can be used:
if ( fgetline ( buffer, sizeof buffer, in ) != -1 ) {
/* ... */
}
Or if one chooses to make it a standard interface with simply a negative failure result rather than a strict -1:
if ( fgetline ( buffer, sizeof buffer, in ) < 0 ) {
/* ... */
}
fgetline already calls strlen as a part of its internal behavior, so there's no extra overhead by changing the return type.
fgetline already returns an integer, so the change required to return a length is minimal:
int fgetline ( char *str, int n, FILE *in )
{
int last;
if ( fgets ( str, n, in ) == NULL )
return -1;
last = strlen ( str ) - 1;
if ( str[last] == '\n' )
str[last] = '\0';
return last;
}
My reasoning is that the usefulness of a string length outweighs the usefulness of a pointer that you already have.