我正在嘗試將SIP標頭解析成一行。我通過逐行遍歷字符串來完成此操作。每個標題應該用新的一行字符分隔。逐行讀取C字符串
輸入字符串將類似於這樣:
INVITE sip:[email protected] SIP/2.0
Via: SIP/2.0/UDP pc33.server1.com;branch=z9hG4bK776asdhds Max-Forwards: 70
To: user2 <sip:[email protected]>
From: user1 <sip:[email protected]>;tag=1928301774
Call-ID: [email protected]
CSeq: 314159 INVITE
Contact: <sip:[email protected]>
Content-Type: application/sdp
Content-Length: 142
我的代碼:
void readlines(char *str){
int i;
int reset;
char current_line[500];
char tmp = 0;
for(i=0; i<strlen(str); i++){
tmp = str[i];
if (tmp == '\n'){
strncpy(current_line, str+tmp, i);
strcat(current_line, '\0');
printf("current line = %s", current_line);
}
}
}
在我的代碼塊,如果你能看到的。在if塊中,我打印出當前行作爲測試我的解決方案的便宜方法,但此打印語句的結果是什麼都沒有。也許我對c如何解釋角色的理解還不完備。
看一看在'strtok'功能 –
感謝您的建議,不幸的是我已經看過這個功能。從我的理解來看,它不是線程安全的,這是我的一個要求。 – btald1331
我發現並沒有意識到的一個問題是,我正在通過將命令行參數傳遞給\ n來測試此函數。但是我通過測試字符串的方式是將字符\ n作爲字面而不是新行字符 – btald1331