Re: removing newline character from the buffer read by fgets
- From: "junky_fellow@xxxxxxxxxxx" <junky_fellow@xxxxxxxxxxx>
- Date: 28 Nov 2006 01:54:46 -0800
On Nov 28, 1:59 pm, Richard Heathfield <r...@xxxxxxxxxxxxxxx> wrote:
junky_fel...@xxxxxxxxxxx said:
<snip>
thanks everyone for your help. In fact, I don't want to use strlen() orway to distinguish between a line that has been read completely and a line
strchr()
(for efficiency reasons) to remove the newline character.
Based of Richard's suggestion, I tried to write my own version of
fgets()
that will not put newline character to the input buffer passed.
I am sure, the people here will find lots of problems in my code. All
comments
are welcome.The principal objection I have to your code is that it fails to provide a
that has been read only partially because of insufficient space in the
buffer.
For that I would change the function to return the number of bytes
read.
If user requested n bytes and bytes read is equal to (n-1), it means
insufficient
space. Is this ok ? Or am I missing something ?
char *
my_fgets(char *string, int n, int *bytes_read, FILE *fp)
{
int ch;
int count = 0;
while(count < (n - 1)) {
ch = fgetc(fp);
if( ch == EOF ) {
break;
}
else if( ch == '\n' ) {
break;
}
else {
string[count] = ch;
}
count++;
}
string[count] = '\0';
*bytes_read = count;
if( ch == EOF )
return(NULL);
else
return(string);
}
.
- Follow-Ups:
- Re: removing newline character from the buffer read by fgets
- From: Richard Heathfield
- Re: removing newline character from the buffer read by fgets
- References:
- removing newline character from the buffer read by fgets
- From: junky_fellow@xxxxxxxxxxx
- Re: removing newline character from the buffer read by fgets
- From: Richard Heathfield
- Re: removing newline character from the buffer read by fgets
- From: junky_fellow@xxxxxxxxxxx
- Re: removing newline character from the buffer read by fgets
- From: Richard Heathfield
- removing newline character from the buffer read by fgets
- Prev by Date: Re: I am studying c myself .Which books I should read?
- Next by Date: Re: Urgently required
- Previous by thread: Re: removing newline character from the buffer read by fgets
- Next by thread: Re: removing newline character from the buffer read by fgets
- Index(es):
Relevant Pages
|