嘿,我正在创建一个发送/接收文件的简单程序,我的代码发送文本文件但是当涉及到二进制时它开始出错,代码:
static void
send_event(conn,file)
void *conn;
void *file;
{
FILE *f;
char *buffer;
int32_t block_size;
int32_t size;
size_t __read;
ConnectionQueue *q;
f = (FILE *)file;
q = (ConnectionQueue *)conn;
block_size = conf_getint("transfer:block_size");
if (block_size <= 1 || block_size > 1024)
{
abort();
return;
}
buffer = (char *)MyMalloc(block_size);
if (!q || !f)
return;
fseek(f,0L,SEEK_END);
size = ftell(f);
if (size == 0L)
{
send_socket(q->conn,"RECEIVE: 302 FSE");
return;
}
fseek(f,0,SEEK_SET);
while (true)
{
if (q->abort)
{
send_socket(q->conn,"RECEIVE: File transfer aborted\n");
if (f)
fclose(f);
f = NULL;
MyFree(buffer);
return;
}
__sleep(100);
__read = fread(buffer,sizeof(char),512,f);
if (__read <= 0)
{
send_socket(q->conn,"RECEIVE: EOF\n");
break;
}
if (*buffer == '\0')
{
send_socket(q->conn,"RECEIVE: EOF\n");
break;
}
send_socket(q->conn,"RECEIVE: %s\n",buffer);
}
send_socket(q->conn,"RECEIVE: 915 EOF\n");
fclose(f);
f = NULL;
MyFree(buffer);
}
固定:请检查我的回答\ /
答案 0 :(得分:2)
K&amp; R语法和void *
参数有什么用?
static void send_event( ConnectionQueue * conn, FILE * file) {
....
在二进制文本与文本上,通常这是因为您使用“r”而不是“rb”作为模式打开文件。
__read = fread(buffer,sizeof(char),512,f);
您应该使用block_size
而不是512
。
if (*buffer == '\0')
...
send_socket(q->conn,"RECEIVE: %s\n",buffer);
你的“二进制文件”可能包含0 - 这不是一个好的EOF标记,如果你在strlen
中使用send_socket
,你的数据会在你的第一个0处被截断缓冲液中。
答案 1 :(得分:0)
这修复了它 - &gt; Send binary file in HTTP response using C sockets