我遇到了字符字节数组的问题。我正在创建文件传输程序,它通过 TCP 套接字传输二进制数据。所以,当我从块中获取数据时,我会将它们保存到临时容器中,然后我必须添加某个地方来保存整个数据。我试过 std::vector 但效果不好(或者我用错了。)
size_t nbytes = 0;
char buffer[5]; //temporary container.
int result = 0;
std::vector<char> abc;
if (ioctl(sockfd, FIONREAD, (char*)&nbytes) < 0)
{
printf("[-] Error getting available data.\n");
return -1;
}
printf("[*] Bytes available: %lu\n", nbytes);
while(true)
{
if(nbytes > sizeof(buffer))
{
result = recv(sockfd, buffer, sizeof(buffer), 0);
for(int i = 0; i < result; i++)
{
abc.push_back(buffer[i]); //big data causes memory corruption.
}
nbytes -= result;
continue;
}
else if(nbytes <= sizeof(buffer) && nbytes != 0)
{
result = recv(sockfd, buffer, nbytes, 0);
for(int i = 0; i < result; i++)
{
abc.push_back(buffer[i]); //big data causes memory corruption.
}
break;
}
else
{
result = 0;
break;
}
}
printf("Data Received: %s", &abc[0]);