S
santosh
CBFalconer said:Barry said:CBFalconer said:santosh wrote:
Bill Cunningham wrote:
You code and the suggestions of others hav prompted me to check
fgets more closely. I guess it adds the newline. Now the \0 Is
added by my understanding by the compiler to a string and that's
the only time \0 is added.
No. In this case, it's fgets that adds the terminating null
character. The compiler is not the only entity that adds null
characters. Several standard library functions also do this.
In your case the problem is not the '\0' but the '\n' before it.
Use strchr to find and remove it before doing the comparison
with strcmp.
That's the slow way. Since fgets always ends operation when it
receives a '\n', any such character is at the end of the line
(otherwise it is a maximul line, and not complete). Therefore
the code:
lgh = strlen(s);
if ('\n' == s[lgh]) s[lgh] = '\0';
Why do you think strlen is faster than strchr? Both step through the
string looking for something. strchr will usually stop looking one
character sooner.
strchr has to check each value against '\n'. strlen just looks for
a zero. Something like:
s = str;
while (*s++) continue;
return s-str-1;
while strchr has make the loop portion:
while ('\n' - *s++) continue;
which does a lot more many times. Zero is usually detectable by
hardware.
I doubt that the code is all that different under most modern hardware.
In anycase, your suggestion to use strlen and look behind is a classic
case of micro-optimisation that's frequently condemned in this group.
Also note that in your code above the expression s[lgh] will yield the
terminating null character of the string in 's', not the '\n'
character, if any.
There is also a complication returning the "NULL if not
found".
Which is exactly what we want to know, and which is what you manually
did above.