use*_*173 1 c sockets fopen send fread
我使用此代码为我的小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);
}
Run Code Online (Sandbox Code Playgroud)
它适用于文本,但不适用于jpeg文件.收到的图像文件已损坏.
fread不保证每次读取时都填充缓冲区,所以你应该只给出你send的字节数fread.当fread你没有得到一个完整的缓冲区时,你可能会提前摆脱循环.尝试类似的东西:
while (( result = fread( buff, 1, buff_size, p_file )) > 0 ) {
send( sock_fd, buff, result, 0 );
}
Run Code Online (Sandbox Code Playgroud)