2016-04-21 246 views
1

當我使用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[]以避免意外的字符?

+1

到底是什麼'Char'? –

+0

任何初始化問題? 'strcat()'可能會失敗OW。 –

+1

'output'在初始化之前使用。用valgrind運行你的程序來檢測這樣的錯誤。 –

回答

0

1- output

strcat(output, buf); 

2- memset使用的未初始化想要一個指針和buf已經(衰變爲)一個指針

memset(&buf, 0, sizeof(buf)); 

應該是

memset(buf, 0, sizeof(buf)); 

3-如果count == 80那麼你h AVE在你的緩衝區後NUL沒有空間,聲明bufchar buf[81];(或read 79字節),不要忘了結束與\0您的字符串後read()

buf[count] = '\0'; 
+0

從插座讀取時來自哪裏的迷路角色? –

+0

@EhteshChoudhury'output'太小了。當你添加超過80個字符時,你會得到未定義的行爲。 –

+0

'buf'不保證以null結尾。 「count」是確定已將多少個字節裝入緩衝區的唯一方式。 str *調用是完全不可用的,特別是如果正在傳輸的數據中嵌入了零字節。 –