Re: removing newline character from the buffer read by fgets





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() or
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
way to distinguish between a line that has been read completely and a line
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);
}

.



Relevant Pages

  • Re: fpurge/fflush
    ... if you dont mind to explain: ... then loops through the stream until it gets either EOF or a newline character. ... values get promoted straight back to int anyway. ...
    (comp.lang.c)
  • Re: Problem with Expect for Windows
    ... eithout adding any newline character." ... Since a readcall that returns zero bytes is considered an EOF in Unix, typing ^D at the ... ^Z in Windows is actually a character that is read out of the stream and serves to mark an EOF, left over from CP/M, which didn't save actual file sized down to the byte, so text files needed some way of specifying "no more valid data in this sector" in the last sector. ...
    (comp.lang.tcl)
  • Re: fpurge/fflush
    ... then loops through the stream until it gets either EOF or a newline character. ... The casts to (char) are useless; ... values get promoted straight back to int anyway. ...
    (comp.lang.c)
  • K&R2 ex 1-8
    ... whose simple request is to write a program that counts blanks, tabs and ... int main ... newline character. ...
    (comp.lang.c)
  • Re: K&R2 ex 1-8
    ... > whose simple request is to write a program that counts blanks, ... void retrun (int); ... > newline character. ... I took this as a request for code review. ...
    (comp.lang.c)