1

I am trying to read from a socket into a buffer until a certain character is reached using read(fd, buf, BUFFLEN).

For example, the socket will receive two lots of information separated by a blank line in one read call.

Is it possible to put the read call in a loop so it stops when it reaches this blank line, then it can read the rest of the information later if it is required?

hmjd
  • 120,187
  • 20
  • 207
  • 252
DMcB1888
  • 171
  • 1
  • 3
  • 10
  • If I have correct interpretation of your problem,you wanna display the first lot of info then idle a couple of seconds for the next one? – jasonkim Feb 22 '12 at 16:33

2 Answers2

4

A simple approach would be to read a single byte at a time until the previous byte and the current byte are new-line characters, as two consecutive new-line characters is a blank line:

size_t buf_idx = 0;
char buf[BUFFLEN] = { 0 };

while (buf_idx < BUFFLEN && 1 == read(fd, &buf[buf_idx], 1)
{
    if (buf_idx > 0          && 
        '\n' == buf[buf_idx] &&
        '\n' == buf[buf_idx - 1])
    {
        break;
    }
    buf_idx++;
}

Any unread data will have to be read at some point if newly sent data is to be read.

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • A character at a time was my initial thought as well, but I'm having difficulty getting it to read it one at a time: inline ` int rlen; int i = 0; while ((rlen = read(proxyFd, &buf[i], 1)) > 0) { if (strstr(&buf[0], "\n\n")) { printf("bingo\n"); break; } i += rlen; } ` – DMcB1888 Feb 22 '12 at 16:21
  • @DMcB1888, you only ever comparing the first two characters in `buf` to `"\n\n"` as you use `buf[0]`. Try `strstr(&buf[i - 1], "\n\n")` but **make** sure `i > 0`. – hmjd Feb 22 '12 at 16:26
0

You still need to read from the socket if you want to access this information later, otherwise it will be lost. I think best implementation would be to keep looping reading from the socket, while another process/thread is launched to perform any operation you want when a blank like is received.

m0skit0
  • 25,268
  • 11
  • 79
  • 127