开发者

What is bad file descriptor in c?

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)
  {
  开发者_如何学C 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 socket
  • filed => file descriptor

and I sure that file descriptor is valid.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜