本人最近在写一个C-S结构的文件传输程序,关键的文件传输部分如下:
ssize_t readall(int fd, void *buf, size_t *len)
{
size_t nleft;
ssize_t nread;
ssize_t total;
char *ptr;
ptr = buf;
nleft = *len;
total = 0;
FILE *fp;
if ((fp = fdopen(fd,"r")) == NULL)
{
perror("fdopen error\n");
exit(1);
}
while( nleft > 0)
{
/*if((nread = read(fd,ptr,*len)) == -1)
{
perror("readall");
break;
}*/
if ((nread = fread(ptr,sizeof(char),*len,fp)) == -1)
{
perror("readall");
break;
}
if(nread ==0)
break;
nleft -= nread;
ptr += nread;
total += nread;
*len = nleft;
}
*len = total;
return (nread==-1)?-1:0;
}
ssize_t writeall(int fd, void* buf,size_t *len)
{
size_t nleft;
ssize_t nwrite;
ssize_t total;
const char *ptr;
ptr = buf;
nleft = *len;
total = 0;
FILE *fp;
if((fp = fdopen(fd,"w")) == NULL)
{
perror("fdopen error\n");
exit(1);
}
while( nleft > 0)
{
/*if((nwrite = write(fd,ptr,*len))== -1)
{
perror("write all");
break;
}*/
if ((nwrite = fwrite(ptr,sizeof(char),*len,fp)) == -1)
{
perror("write all\n");
break;
}
nleft -= nwrite;
ptr += nwrite;
total += nwrite;
*len = nleft;
}
*len = total;
return (nwrite==-1)?-1:0;
}
现在遇到一个奇怪的问题,如果在这个程序中使用read/write函数,则文件传输正常,
若改为标准IO函数,使用fread/fwrite函数则出现问题.经过检察发现服务器端的读文件发送到Socket没有问题,但客户端无法从socket中读出数据.请教各位这是什么原因? |