Reputation: 97
I came across a weird problem in c programming today. I wrote a program for server client communication and applied the string comparison function on it but the function doesn't work if I compare a string with stuff inside buf. I also checked if data in buf is different than what I am entering after a few iteration but results were negative and the data is the same as I am entering. Then why does strcmp
is not working. Here is the code:
char buf[1024];
while(1)
{
int readbytes=read(communFd,buf,1024);
write(STDOUT_FILENO,buf,readbytes);
if(!strcmp(buf,"exitChat"))
{
printf("Chat terminating...\n");
break;
}
}
Regards
Upvotes: 0
Views: 933
Reputation: 121971
read()
does not null terminate the buffer which strcmp()
depends upon, you must do this explicitly:
int readbytes=read(communFd,buf,1023); /* Read one less for null terminator. */
if (readBytes != -1)
{
buf[readBytes] = 0;
if(!strcmp(buf,"exitChat"))
{
}
}
Or, as mentioned by others use a different function that does not depend upon the presence of the null terminator character.
Note that read()
does not guarantee that the requested number of bytes is read and it is not considered an error if less bytes is read. From the linked reference page:
On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. On error, -1 is returned, and errno is set appropriately. In this case it is left unspecified whether the file position (if any) changes.
To ensure that a full message has been received you will need to add data to text being sent so the receiver knows when it has received a complete message. This could be:
\n
character to indicate the end. The structure of the code would change to call read()
in a loop until the \n
is found while appending each byte read to an array.Upvotes: 6
Reputation: 30273
Since you have readbytes
, compare only that many bytes:
if(!strncmp(buf,"exitChat",readbytes))
Upvotes: 1
Reputation: 42175
strcmp
will compare two null-terminated char arrays. read
will not null-terminate buffers you read from a file descriptor. Unless you know there should be '\0'
bytes in your file, you could try using strncmp(buf,"exitChat", sizeof("exitChat")-1)
instead.
Upvotes: 2