Re: read(), size of array, null-terminate

From: Barry Margolin (barry.margolin_at_level3.com)
Date: 05/29/03


Date: Thu, 29 May 2003 18:09:06 GMT

In article <20030529135735.249dec78.david@wmol.com>,
David Hill <david@wmol.com> wrote:
>On Thu, 29 May 2003 13:46:35 -0400
>David Hill <david@wmol.com> wrote:
>
>> Hello -
>> I am expecting data in the form of
>> :PACKET_TYPE:data goes here
>> where PACKET_TYPE is an integer of 4 digits.
>>
>> #define MAX_DATA_LEN 1024
>> #define MAX_TYPE_LEN 4
>> #define MAX_PACKET_LEN MAX_DATA_LEN + MAX_TYPE_LEN + 2 /* 2 for the 2 colons */
>>
>> is the following the proper way to null terminate the received data on
>a socket fd?
>>
>> /* example code (no error checking) */
>> char buf[MAX_PACKET_LEN + 1];
>> ssize_t bytes;
>>
>> bytes = read(fd, buf, sizeof(buf)-1);
>> buf[bytes+1] = '\0';
>>
>> /* END */
>>
>> Thanks
>> - David
>
>
>or should i do +3 (2 for colons, 1 for '\0')

Yes.

>char buf[MAX_PACKET_LEN];
>ssize_t bytes;
>
>bytes = read(fd, buf, sizeof(buf));
>buf[bytes] = '\0';

This is the correct way to null-terminate it.

Note that you need to call read() in a loop to make sure you get all the
data; there's no guarantee that the entire packet will be returned in a
single call to read() (unless this is a datagram socket). So you'll
probably want to keep appending it to the buffer, summing up the bytes, and
then null-terminate it once you've gotten everything (how you determine
that you've gotten "everything" is dependent on the application protocol).

-- 
Barry Margolin, barry.margolin@level3.com
Level(3), Woburn, MA
*** DON'T SEND TECHNICAL QUESTIONS DIRECTLY TO ME, post them to newsgroups.
Please DON'T copy followups to me -- I'll assume it wasn't posted to the group.