當我使用read()
套接字從服務器檢索字節時,我在字符中發現了一些意想不到的情況。從C讀取套接字
下面是我的代碼:
Char buf[80];
Char output[80];
if ((count = read(socket_d, buf, 80)) == -1) {
perror("Error on read call");
exit(1);
}
strcat(output, buf);
printf("Client read %d bytes\n", count);
while (count==80) {
memset(&buf, 0, sizeof(buf));
if ((count = read(socket_d, buf, 80)) == -1) {
perror("Error on read call");
exit(1);
}
printf("Client read %d bytes\n", count);
strcat(output, buf);
}
/* print the received message */
printf("\n%s\n\n", output);
如下輸出:
Client read 80 bytes
Client read 80 bytes
Client read 8 bytes
Your messages:
1:From User1, 04/21/16 02:12 AM, MSG1
2:From User2, 04/21/16 02:162 AM, MSG2
3:From User2, 04/21/16 02:12 AM, MSG3
4:From User1, 04/21/16 02:12 AM6, MSG4
的期望輸出應該是:
Client read 80 bytes
Client read 80 bytes
Client read 8 bytes
Your messages:
1:From User1, 04/21/16 02:12 AM, MSG1
2:From User2, 04/21/16 02:12 AM, MSG2
3:From User2, 04/21/16 02:12 AM, MSG3
4:From User1, 04/21/16 02:12 AM, MSG4
似乎有所示意想不到char('6')
buf[]
在第二個循環中。
由於我定義了每個時間的大小read()
套接字,所以我想循環讀取,直到讀取的數量小於limit_size
,然後輸出。
在迴路中我應該如何處理buf[]
以避免意外的字符?
到底是什麼'Char'? –
任何初始化問題? 'strcat()'可能會失敗OW。 –
'output'在初始化之前使用。用valgrind運行你的程序來檢測這樣的錯誤。 –