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
read()does not null terminate the buffer whichstrcmp()depends upon, you must do this explicitly: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: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:
\ncharacter to indicate the end. The structure of the code would change to callread()in a loop until the\nis found while appending each byte read to an array.