On 6 Jan 2005 03:54:14 -0800,
se********@yahoo.co.in
<se********@yahoo.co.in> wrote:
I am working under a Linux environment, and I want to
"read stream up to next delimiter". It looks like linux
doesnt't have a function such as bgets()
Nor does standard C, which is what's on topic here.
All i need is,
reading characters from stream into buffer until either
count is exhausted or one of the characters in breakstring
is encountered in the stream. The read data is terminated
with a null byte (' \0') and a pointer to the trailing null
is returned. If a breakstring character is encountered,
the last non-null is the delimiter character that terminated
the scan. Any library function available to achieve it
how to do it??
No, but it's easy enough to code portably:
#include <string.h>
#include <stdio.h>
/**
* Get a buffer from a stream until either the length is met or
* a character in breakstr is found. The buffer will be nul
* terminated.
*
* \param fp stream pointer
* \param buff buffer pointer
* \param len size of the buffer including trailing nul
* \param breakstr string of characters to act as trailing delimiters
*
* \return number of characters in buffer, excluding trailing nul
*/
int getToDelimiter(FILE *fp, char *buff, int len, const char *breakstr)
{
int count = 0;
int ch;
while (count < len-1 && (ch = fgetc(fp)) != EOF)
{
*buff[count++] = ch;
if (strchr(breakstr, ch))
break;
}
*buff[count] = '\0';
return count;
}
(Feel free to use it, mess with it or whatever. Note that as written if
a nul (0) character is read from the stream it will always be treated as
a terminator -- why this happens and how it can be corrected is left as
an exercise for the reader. I give no warranty of fitness for purpose,
safety in mission-critical applications, or anything else; if it causes
you computer to catch fire, your pet gerbil to die, your car to break
down, or starts a global thermonuclear war I'm not responsible, I wasn't
there, it wasn't me it was some other cat, and anyway I meant to do
it. I didn't spell check it either, any spells are your problem, I'm
not a witch...)
Chris C