c中的坏文件描述符是什么?
这是我想要读取文件的函数代码:
int sendByByte(int filed,int sockfd,int filesize)
{
int i=0;
int sent=0;
char buf[BUFSIZE];
while(i<filesize)
{
printf("fd is : %d\n",filed);
printf("i: %d\n",i);
int byte_read=read(filed,buf,BUFSIZE);
if(byte_read == -1)
{
printf("MOSHKEL dar read\n");
return -1;
}
int byte_send=send(sockfd,buf,byte_read,0);
if(byte_send==-1)
{
printf("MOSHKEL dar send\n");
return -1;
}
close(filed);
i+=byte_read;
sent+=byte_read;
}
return sent;
}
问题是当i=0
它工作并读取文件但read()
返回-1时。 代码有什么问题?
socketfd
=>;服务器的套接字filed
=>;文件描述符
,我确信该文件描述符是有效的。
This is my code of function that wants to read file:
int sendByByte(int filed,int sockfd,int filesize)
{
int i=0;
int sent=0;
char buf[BUFSIZE];
while(i<filesize)
{
printf("fd is : %d\n",filed);
printf("i: %d\n",i);
int byte_read=read(filed,buf,BUFSIZE);
if(byte_read == -1)
{
printf("MOSHKEL dar read\n");
return -1;
}
int byte_send=send(sockfd,buf,byte_read,0);
if(byte_send==-1)
{
printf("MOSHKEL dar send\n");
return -1;
}
close(filed);
i+=byte_read;
sent+=byte_read;
}
return sent;
}
The problem is when i=0
it works and read file but then read()
returns -1.
What is the problem of the code?
socketfd
=> server's socketfiled
=> file descriptor
and I sure that file descriptor is valid.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一次迭代后,您
close(filed)
(第 22 行),导致所有进一步的读取失败。将
close
调用移到循环之外,甚至更好:让调用者关闭文件描述符,因为他打开了它。After the first iteration you
close(filed)
(line 22), causing all further reads to fail.Move the
close
call outside the loop, or even better: Let the caller close the file descriptor, since he opened it.