1

这是我想要读取文件的函数代码:

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=> 文件描述符

我确定文件描述符是有效的。

4

1 回答 1

4

在第一次迭代之后close(filed)(第 22 行),导致所有进一步的读取失败。将close调用移到循环之外,甚至更好:让调用者关闭文件描述符,因为他打开了它。

于 2010-10-21T06:42:06.593 回答