2010-10-21 113 views
1

這是我的功能代碼,想讀文件:什麼是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 =>文件描述符

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

+0

歡迎來到SO。這個問題與C本身無關,文件描述符是一個操作系統功能。請相應地更改題目和標題。 – 2010-10-21 07:01:08

+0

添加了posix標籤 – 2010-10-21 07:12:38

回答

4

第一次迭代後,您close(filed)(第22行),導致所有進一步的讀取失敗。 將close調用移到循環外部,或者更好:讓調用者關閉文件描述符,因爲他打開了它。