tags:

views:

53

answers:

2

Hello,

I have:

char buf[320];

read(soc, buf, sizeof(buf));
//print buf;

However, sometimes the reply is much bigger then 320 characters, so I'm trying to run the read in a loop to avoid taking up too much memory space. I tried read(soc, buf, sizeof(buf)) but that only prints the same first x characters over again. How would I print the leftover characters that did not fit into the first 320 characters in a loop?

Thanks

A: 
Nikolai N Fetissov
+1  A: 

Change your loop to something like:

while(1)
{
    int numread;

    if ((numread = read(soc, buf, sizeof(buf - 1))) == -1)
    {
        perror("read");
        exit(1);
    }

    if (numread == 0)
       break;

    buf[numread] = '\0';

    printf("Reply: %s\n", buf);
}

for the reasons Nikola states.

Duck
Better make the read() call take sizeof(buf)-1 instead of sizeof(buf), or that null-terminator byte that gets written just before the printf is going to be written after the end of the array... that would be a bad thing.
Jeremy Friesner
Thanks Jeremy. Never code and watch Terminator movies at the same time.
Duck