问题描述
编辑:while循环条件从> 0
更改为!=0
。打印内容后,在终端上还将输出2条或更多条换行符,但文件中没有。
我正在从客户端到服务器传输文件。内容已成功传输,但在接收时不会退出while循环。我的一会儿状况不对吗?强制停止程序后,我可以看到该文件实际上已成功复制,将所有内容写入该文件后,它不会在while循环中退出。
这是我遇到麻烦的代码:
ssize_t bytes_read = 0;
int error;
while((bytes_read = read(sd,buf,sizeof(buf))) != 0){
printf("writing: %s\n",buf);
if((error = fwrite(buf,1,bytes_read,fp)) < 0)
{
printf("error");
}
if((bytes_read = read(sd,sizeof(buf))) < 0){
break;
}
}
试图将其保持在最低限度,因为我敢肯定,这里有些错误。
编辑:我尝试使用一个较大的文件,它似乎到处都缺少一些内容,但是格式不一致。
编辑:这是客户端。
else if(strcmp(shortCommand,"put") == 0){
char *tmp = buf + 4;
char filename[MAX_BLOCK_SIZE];
strcpy(filename,"filename ");
strcat(filename,tmp);
FILE *fp;
printf("File name: %s\n",tmp);
fp = fopen(tmp,"rb");
if(fp == NULL){
printf("ERROR: Requested file does not exist.\n");
}
else{
printf("Client sending filename...\n");
if ((nw = write(sd,sizeof(buf))) < 0){ //sending the file name to the client first
printf("Error sending client's filename.\n");
}
printf("Client sending file...\n");
size_t bytes_read = 0;
ssize_t bytes_written = 0;
while((bytes_read = fread(buf,sizeof(buf),fp)) != 0){ //sending the file contents
if ((bytes_written = write(sd,bytes_read)) < 0){
printf("Error sending client file.\n");
}
}
fclose(fp);
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)