Fgets (K & R)

I am new to programming, starting with Objective-C, but decided to go back to the basics before moving on. I spend some time in C and struggle with pointer confusion. My question is how K & R says fgets is implemented (p165, 2nd ed.). The code below is straight from the text with a few of my comments.

char* fgets(char* s, int n, FILE *iop) { register int c; register char* cs; cs = s; while(--n > 0 && (c = getc(iop)) != EOF) { // put the input char into the current pointer position, then increment it // if a newline entered, break if((*cs++ = c) == '\n') break; } *cs = '\0'; return (c == EOF && cs == s) ? NULL : s; } 

1) We pass char * s to the fgets function, in which we store user input. Why is it necessary to declare a local char * cs - and then initialize it to s? Why can't we directly manipulate / add to s inside the if statement? Seeing how cs is initialized with s, does the character add exactly the same thing to cs?

2) Related to the above ... When the function returns, a test is run to see cs == s. Why is this necessary?

I think that maybe I am missing something very fundamental - I really tested SO and Google, but I can’t understand. Thank you

+8
c pointers
source share
1 answer

This is due to checking the last line, cs == s . This comparison checks the changed cs pointer to the original s to see if we have read any character. If we do not, then we return NULL.

Using cs over the entire source pointer s is saved. If s were directly manipulated ( *s++ instead of *cs++ ), we would need to find another way to check if any characters were read.

It can also be argued that it is good practice to leave functional parameters on their own and treat them as const . Some programmers follow this practice as a way to improve code clarity.

+7
source share

All Articles