微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

客户端读取的字节数超过了C中发送的字节数-Linux

如何解决客户端读取的字节数超过了C中发送的字节数-Linux

编辑:我试图将文件从服务器发送到客户端。当我发送一个44字节的文件时,客户端在第一次迭代中读取256个字节(这是char数组buf的大小),而在下一次迭代中读取其余的44个字节。为什么它最初不读取44个字节?

客户端代码段(接收文件):

while((bytes_read = read(sd,buf,sizeof(buf))) > 0){ //receving file contents and writing to file
                    printf("DEBUG B: read=%zd\n",bytes_read);
                    fwrite(buf,1,bytes_read,fp);
                    total_bytes_read += bytes_read;
                printf("DEBUG C: total=%zu\n",total_bytes_read);
                if(ferror(fp)){
                    perror("Error when writing to file\n");
                    exit(1);
                    fclose(fp);
                }
                //printf("Filesize is: %zu \n",filesize);
                if(total_bytes_read == filesize){
                    break;
                }
                }
                printf("The client has received the file\n");
              }

服务器部分(发送文件):

strcpy(buf,"no issues");
                if((y = write(sd,sizeof(buf))) < 0){
                    perror("Error reporting back to client\n");
                }
            
            fseek(fp,SEEK_END);
            filesize = ftell(fp);
            fseek(fp,SEEK_SET);
            printf("Sending file size\n");
            
            if((write(sd,&filesize,sizeof(filesize))) < 0){ //sending filesize
                printf("error sending file size\n");
            }
            
            printf("Filesize is: %zu \n",filesize);
            printf("Sending file\n");
            
            while((bytes_read = fread(buf,sizeof(buf),fp)) > 0){ //sending file contents
                printf("DEBUG A: Bytes read %zu \n",bytes_read);
                if ((bytes_written = write(sd,bytes_read)) < 0){
                    printf("Error sending server file.\n");
                }
                printf("DEBUG B: Bytes sent %zu \n",bytes_written);
                total_bytes_sent += bytes_written;
                printf("Total bytes sent %zi \n",total_bytes_sent);
            }
            printf("File has been sent\n");
            fclose(fp);
         }

如果需要更多代码,我会发布它。非常感谢您的帮助!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。