嗯 - 临时文件的优点确实是 - 更简单的内存管理。在许多成熟/现代的操作系统上 - 像 /tmp 这样的短期文件的开销非常小(而且你作为开发人员的时间很昂贵)。如果您对文件大小有某种想法 - 一种非常常见的方法如下所示。
但究竟你想要什么取决于内存管理。而且很容易重新发明轮子。
避免这种情况的一个好方法是使用类似http://apr.apache.org/ APR Commons - 即 apr_socket_recv() 和相关的内存管理 (http://apr.apache.org/docs/apr/1.4/ group_ apr _network__io.html#gaa6ee00191f197f64b5a5409f4aff53d1)。一般来说,这是一个长期的胜利。
德。
// On entry:
// buffp - pointer to NULL or a malloced buffer.
// lenp - pointer for the length; set to 0 or the length of the malloced buffer.
// On exit
// return value < 0 for a fault, 0 for a connection close and > 0 for
// the number of bytes read.
// buffp will be filled out with the buffer filled; lenleftp with the bytes left
// (i.e not yet used).
// If post call *buffp != NULL you need to release/clean memory.
//
ssize_t sockread(..., unsigned char * * buffp , ssize_t * lenleftp) {
if (!buffp || !lenleftp)
return -1; // invalid params
// claim memory as needed.
if (*buffp == 0) {
*lenleftp = 16K;
*buffp = malloc(*lenleftp);
}
if (!*buffp || !*lenleftp)
return -2; // invalid params
ssize_t used = 0;
while(1) {
ssize_t l = recv(..., *buffp, *lenleftp - used, ..);
if (l < 0) {
// ignore transient errors we can retry without much ado.
if (errno == EAGAIN || errno == EINTR)
continue;
free(*buffp); *buffp = *lenleftp = NULL;
// report a fail.
return -3;
}
// we simply assume that a TCP close means we're done.
if (l == 0)
break;
used += l;
// increase buffer space as/when needed.
//
if (used >= lenleftp) {
*lenleftp += 32K;
*buffp = realloc(lenleftp);
};
}
// we're assuming that a read == 0-- i.e. tcp stream done means
// we're done with reading.
//
*lenleftp -= used;
return used;
}