Re: Question regarding fgets and new lines



Eric Sosman wrote:
mellyshum123@xxxxxxxx wrote:

I need to read in a comma separated file, and for this I was going
to use fgets. I was reading about it at http://www.cplusplus.com/ref/
and I noticed that the document said:

"Reads characters from stream and stores them in string until
(num -1) characters have been read or a newline or EOF character
is reached, whichever comes first."

.... snip ...

If you've used malloc() to obtain memory for the buffer,
another possibility is to use realloc() to make the buffer
larger (preserving the already-read portion) and call fgets()
again to read the tail of the line into the tail of the expanded
buffer. If necessary, you can expand again and again until you
finally get a big enough buffer (or run out of memory). In my
opinion it's a little easier to implement this scheme by using
getc() to read a character at a time instead of using fgets()
to read a batch of characters, but either way it's fairly
straightforward.

Or simply download and use the public domain ggets, at:

<http://cbfalconer.home.att.net/download/>

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>


.



Relevant Pages

  • Re: scanf problem with intaking a string *PLS. HELP*
    ... >> if (fgets(buffer, sizeof buffer, stream)) ... > when fgets knew perfectly well that it truncated the buffer? ... where N is the number of characters in the ...
    (comp.lang.c)
  • Re: 2D array of structures
    ... The way gets works is that you pass it a pointer to a buffer but it has absolutely no knowledge of how long the buffer is. ... So you pass a pointer to a buffer 10 characters long and the user enters 10 character and gets writes off the end of the buffer stomping over some random piece of data. ... fgets, fgetc or getc are generally good starting points. ... So I'm the newbie and I have to get used to ...
    (comp.lang.c)
  • Re: sorting the input
    ... In this case the last two characters ... There is a '\n' in the string returned from fgets only when the amount ... of data read leaves at least two unused bytes in the buffer. ... (a frequent student assignment), you could process the partial line ...
    (comp.lang.c)
  • Re: string length questions related to fseek
    ... > take you up to 257 characters required to store all the data. ... fgets() is the total size of the buffer, ... not store anything at all outside the buffer. ... That's a C feature, not a Unix feature. ...
    (comp.lang.c)
  • Re: Is this string input function safe?
    ... return a pointer to mallocated memory holding one input string, ... See my comment after your call to fgets. ... char* malloc_getstr ... before any characters are read, then the ...
    (comp.lang.c)