接收文件时出错
我有这个代码:
while (1) {
char buffer[4096];
memset(buffer,0,4096);
int bytes_read = recv(client_fd, buffer, sizeof(buffer),0);
if (bytes_read == 0)
break;
if (bytes_read < 0) {
std::cout<< "Error "<<endl;
}
void *p = buffer;
int dest;
dest=open("/root/hello.txt",O_WRONLY);
while (bytes_read > 0) {
int bytes_written = send(dest, buffer, bytes_read,0);
if (bytes_written <= 0) {
std::cout<< "Error2 "<<endl;
}
bytes_read -= bytes_written;
p += bytes_written;
}
}
我正确收到文件。 程序进入循环,其中 cout 为“Error2”,因此发送返回 -1。 问题是将文件写入新的文件描述符,在本例中为名为 dest
的变量。 我该如何解决这个问题?
I have this code:
while (1) {
char buffer[4096];
memset(buffer,0,4096);
int bytes_read = recv(client_fd, buffer, sizeof(buffer),0);
if (bytes_read == 0)
break;
if (bytes_read < 0) {
std::cout<< "Error "<<endl;
}
void *p = buffer;
int dest;
dest=open("/root/hello.txt",O_WRONLY);
while (bytes_read > 0) {
int bytes_written = send(dest, buffer, bytes_read,0);
if (bytes_written <= 0) {
std::cout<< "Error2 "<<endl;
}
bytes_read -= bytes_written;
p += bytes_written;
}
}
I receive the file correctly.
The program goes in loop where the cout is "Error2", so the send returns -1.
The problem is to write the file in a new file descriptor, in this case the variable called dest
.
How can I solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据
send 的手册页(2)
,只能写入套接字,不能写入普通文件;如果您检查了errno
(使用例如perror
),您会看到它被设置为ENOTSOCK
。您应该始终看到正在设置的错误,否则调试只是在黑暗中进行。另外,由于这是 C++,我真的认为您应该使用 C++ 风格的 I/O(
std::ofstream
等)来写入常规文件。According to the manual-page for
send(2)
, it can only write to a socket, not to a regular file; if you had checkederrno
(using e.g.perror
), you would have seen that it gets set toENOTSOCK
. You should always see what error is being set, otherwise debugging is just shooting in the dark.Also, since this is C++, I really think you should use C++-style I/O (
std::ofstream
and so on) to write to a regular file.检查返回值
It应该是一个正整数;其他一切都表明有错误。我的猜测是该文件由于某种原因无法打开。
Check the return value of
It should be a positive integer; everything else indicates an error. My guess is that the file can't be opened for whatever reason.