我可以毫无问题地发送非常大的文本文件。我尝试发送 jpg 等,但它不起作用。文件大小正确。我不知道我错过了什么。我通过在发送到 temp.foo 文件之前写入数据来检查我的读写功能。我检查它,它处理任何事情。
我是这样发送的
for(vector< .... >::iterator it = v.begin(); it!=v.end(); ++it ){
pair<...> p=*it;
send(s,p.first,p.second,0);
}
然后其他程序读取它
for(i = 0; i < size; i+=max){
b= 0;
while (b== 0) {
if ((b = recv(s, buf, max, 0)) == -1) {
perror("recv");
exit(1);
}
}
stringstream ss;
ss << buf;
char * out = (char*)malloc(b);
memcpy(out,buff,numbytes);// Perhaps my error is here?
}
// write function call here
最佳答案
关于处理二进制数据的一些一般要点:
确保以二进制模式打开输入和输出文件,例如
ios::binary
标志或 "rb"或 "wb"格式。默认是文本模式,它会破坏二进制文件中的行尾字符。二进制文件可以有 NUL 字节 (
\0
),这意味着您不能使用处理以 NUL 结尾的字符串的字符串处理函数。 C 字符串不是 NUL 安全的。例如,此代码不会正确填充ss
,因为它将buf
解释为 NUL 终止的字符串:stringstream ss; ss << buf;
此外,在您指出的行中,带有两个 f
的 buff
是拼写错误吗?在其他行中,您使用 f
引用 buf
。
memcpy(out,buff,numbytes);// Perhaps my error is here?
关于c++ - 通过套接字发送二进制文件。文本文件有效,没有别的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12653936/