C 在客户端-服务器套接字连接中正确传输文件

C 在客户端-服务器套接字连接中正确传输文件,c,sockets,file-upload,C,Sockets,File Upload,我编写了以下代码,用于从客户端发送文件: FILE *fp = fopen("video.mp4","rb"); if(fp==NULL) { printf("File opern error"); return 1; } int bytesToWrite=84440670; int bytesWritten=0; while(bytesWritten<bytesToWrite)

我编写了以下代码,用于从客户端发送文件:

FILE *fp = fopen("video.mp4","rb");
        if(fp==NULL)
        {
            printf("File opern error");
            return 1;   
        } 

int bytesToWrite=84440670;
int bytesWritten=0; 
while(bytesWritten<bytesToWrite)
    {
        int m=minimum(256,bytesToWrite-bytesWritten);
        /* First read file in chunks of 256 bytes or the remaining bytes*/
        unsigned char *buff=malloc(sizeof(char)*m);
        bzero(buff, m);
        int nread = fread(buff,1,m,fp);
        printf("Bytes read %d \n", nread);  
        bytesWritten+=m;   

        /* If read was success, send data. */
        if(nread > 0)
        {
            printf("Sending \n");
            write(sockfd, buff, nread);
        }

        /*
         * There is something tricky going on with read .. 
         * Either there was error, or we reached end of file.
         */
        if (nread < 256)
        {
            if (feof(fp))
                printf("End of file\n");
            if (ferror(fp))
                printf("Error reading\n");
            break;
        }


    }
FILE*fp=fopen(“video.mp4”、“rb”);
如果(fp==NULL)
{
printf(“文件操作错误”);
返回1;
} 
int bytesToWrite=84440670;
int字节数=0;
while(字节写为0)
{
printf(“发送”);
写入(sockfd、buff、nread);
}
/*
*里德有点棘手。。
*要么有错误,要么我们到达了文件的末尾。
*/
如果(nread<256)
{
if(feof(fp))
printf(“文件结束\n”);
if(费罗(fp))
printf(“错误读取\n”);
打破
}
}
以及服务器接收的以下代码:

FILE *fp;
        fp = fopen("receive.mp4", "wb"); 
        if(NULL == fp)
        {
            printf("Error opening file");
            return 1;
        }
        int bytesToRead=84440670;
        /* Receive data in chunks of 256 or remaining bytes */
        int totalbytesread=0;
        while(totalbytesread < bytesToRead)
        {
            int m = minimum(256,bytesToRead-totalbytesread);
            char *recvBuff=malloc(sizeof(char)*m);
            bzero(recvBuff,m);
            bytesReceived = read(newsocfd, recvBuff,m );
            printf("Bytes received %d\n",bytesReceived);
            totalbytesread += bytesReceived;   
            fwrite(recvBuff, 1,bytesReceived,fp);
        }

        if(bytesReceived < 0)
        {
            printf("\n Read Error \n");
        }
文件*fp;
fp=fopen(“receive.mp4”、“wb”);
if(NULL==fp)
{
printf(“打开文件时出错”);
返回1;
}
int bytesToRead=84440670;
/*接收256字节或剩余字节的数据块*/
int totalbytesread=0;
while(totalbytesread
.txt文件的发送工作正常,一些数据在发送其他格式时丢失(例如,.mp4文件的某些结束秒未被发送)。
我不熟悉套接字编程。任何帮助都将不胜感激。

您缺少一个
fclose(fp)。您还可以使用
fflush(fp)
以刷新内容


此外,还有几处内存泄漏和错误处理不当。

我不知道原因,但每次迭代都有一处内存泄漏。