問題描述
c ‑ 刪除前 4 個字節的數據 (c ‑ remove first 4 bytes of data)
I'm reading a packet but I need to strip the first four bytes and the last byte from the packet to get what I need, how would you go about doing this in C?
/* Build an input buffer of the incoming message. */
while ( (len=read(clntSocket, line, MAXBUF)) != 0)
{
msg = (char *)malloc(len + 1);
memset(msg, 0, len+1);
strncpy(msg, line, len);
}
}
The incoming data is a mix of char and int data.
‑‑‑‑‑
參考解法
方法 1:
You can simply start you copy at (line + 4) if line is a char *, which it appears to be. And copy 5 bytes fewer than len, which will ditch the last byte.
I.e. making it pretty explicit (assuming your prior malloc, which leaves some safety at the end of the buffer).
char *pFourBytesIn = (line + 4);
int adjustedLength = len ‑ 5;
strncpy(msg, pFourBytesIn, adjustedLength);
msg[adjustedLength] = '\0';
方法 2:
You can change the address of strncpy
source:
while ( (len=read(clntSocket, line, MAXBUF)) != 0)
{
msg = (char *)calloc(len ‑3, 1); // calloc instead of malloc + memset
strncpy(msg, line+4, len);
}
}
PS: I assumed that line is char*
.
(by txcotrader、DWright、Ramy Al Zuhouri)