Re: removing newline character from the buffer read by fgets



On 28 Nov 2006 00:30:45 -0800, "junky_fellow@xxxxxxxxxxx"
<junky_fellow@xxxxxxxxxxx> wrote in comp.lang.c:



On Nov 28, 11:07 am, Richard Heathfield <r...@xxxxxxxxxxxxxxx> wrote:
junky_fel...@xxxxxxxxxxx said:

Is there any efficcient way of removing the newline character from the
buffer read by
fgets() ?Others here have posted sensible suggestions on the best way to remove the
newline character from the buffer after an fgets call. But if you're really
after efficiency, don't use fgets!

Is there any library function that is similar to fgets() but also tells
how many
bytes it read into the buffer ?No such standard library function exists, but you could write a routine
yourself to do it. It could also have the following characteristics:

1) always reads a complete line (subject to available memory), by expanding
the buffer as and when necessary
2) allows you to re-use the same buffer over and over (like fgets)
3) records and reports the number of bytes read into the buffer per call
4) records and reports the current size of the buffer (*not* the same thing
as the length of the string contained therein)
5) doesn't bother putting a newline on the end, because there's no need,
because of Property 1, and therefore the caller need not remove it

Such a routine is far, far, far simpler to write than you might imagine.


thanks everyone for your help. In fact, I don't want to use strlen() or
strchr()
(for efficiency reasons) to remove the newline character.

"efficiency reasons" is your first mistake. If you're writing your
own implementation as a learning exercise, well and good. If you're
writing your own implementation because you think it will be "more
efficient" than fgets()+strlen(), you are wrong on two counts:

1. It probably won't be more efficient.

2. You probably don't need more efficiency anyway.

After you get your program working properly with the simplest, easiest
to understand implementation, and it runs too slowly, and you use a
profiler or other test method to prove that this implementation is a
serious bottleneck, then and only then consider writing your own
routine for efficiency.

And even then, test again afterwards to see if you have actually
improved efficiency.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~ajo/docs/FAQ-acllc.html
.



Relevant Pages