【问题标题】:sending image file in C [duplicate]用C发送图像文件[重复]
【发布时间】:2013-02-20 16:40:32
【问题描述】:

我使用此代码为我的小型 HTTP 服务器发送二进制文件

/* send binary data to client */

void send_binary(int sock_fd, char *file_name)
{

    int buff_size = 10240;
    char buff[buff_size];
    long file_size;
    FILE *pFile;
    size_t result;
    if ( (pFile = fopen(file_name, "rb")) == NULL){
        error("fopen error\n");
    }

    while( (result = fread(buff, 1, buff_size, pFile)) == buff_size){
        send(sock_fd, buff, buff_size, 0);
        buff[0] = '\0';
    }
    if (result > 0){
        if(feof(pFile)){
            send(sock_fd, buff, result, 0);
        }
        else{
            error("read error\n");
        }
    }
    fclose(pFile);

}

它适用于文本,但不适用于 jpeg 文件。接收到的图像文件已损坏。

【问题讨论】:

  • 发布接收代码...二进制数据可以包含零...您如何确定接收数据的长度?
  • 最好先发送JPEG文件的大小,再发送实际数据。

标签: c sockets send fopen fread


【解决方案1】:

fread 不能保证在每次读取时都填充缓冲区,因此您应该只使用 send fread 给您的字节数。当fread 没有为您提供完整的缓冲区时,您可能会提前跳出循环。尝试类似:

while (( result = fread( buff, 1, buff_size, p_file )) > 0 ) {
    send( sock_fd, buff, result, 0 );
}

【讨论】:

    猜你喜欢
    • 2016-06-21
    • 1970-01-01
    • 2019-05-07
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-08
    • 2012-10-15
    • 1970-01-01
    相关资源
    最近更新 更多