c中的坏文件描述符是什么?

发布于 2024-09-28 06:29:26 字数 726 浏览 1 评论 0原文

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

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 socket
  • filed => file descriptor

and I sure that file descriptor is valid.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凯凯我们等你回来 2024-10-05 06:29:26

第一次迭代后,您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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文