0
votes
/ * fgets:  get at most n chars from iop * / 

char * fgets(char * s, int n, FILE * iop) 
{ 
    register int c;
    register char * cs; 
    cs = s; 
    while (-n > 0 && (c = getc(iop)) != EOF) 
        if (( * cs++ = c) == ′\n′) 
            break; 
    *cs = ′\0′; 
    return (c == EOF && cs == s) ? NULL : s; 
 }

please my question is why cs == s, in the return statement. since fgets is supposed to return NULL, if end of file, or error occured, why isn't the return statement just return (c == EOF) ? NULL : s;

getc, is also a c standard library function, that reads a character, at a time from the file iop points to. the function fgets reads a line from the file iop points to, and returns if successful, the line read, stored in the character array s. returns NULL, if end of file encountered, or error occured

cheers

1
getc, is also a c standard library function, that reads a character, at a time from the file iop points to. the function fgets reads a line from the file iop points to, and returns if successful, the line read, stored in the character array s. returns NULL, if end of file encountered, or error occured - Evan

1 Answers

2
votes

why isn't the return statement just return (c == EOF) ? NULL : s;

Because if cs != s then obviously some bytes were successfully read before end-of-file or an error was encountered, and it would be clearly wrong for fgets() to return NULL if it successfully read something before reaching the end of the file.