stream: replace print/vprint() convenience functions by a FILE* getter

While this will complicate the implementation of streams not based on a fd,
it allows us to unleash the full power of FILE based convenience functions.
This commit is contained in:
Martin Willi
2013-07-18 16:00:28 +02:00
parent 70d1ccec96
commit fbdc65debb
2 changed files with 20 additions and 51 deletions
+17 -37
View File
@@ -35,11 +35,6 @@ struct private_stream_t {
*/ */
int fd; int fd;
/**
* FILE* for convenience functions, or NULL
*/
FILE *file;
/** /**
* Callback if data is ready to read * Callback if data is ready to read
*/ */
@@ -203,45 +198,31 @@ METHOD(stream_t, on_write, void,
add_watcher(this); add_watcher(this);
} }
METHOD(stream_t, vprint, int, METHOD(stream_t, get_file, FILE*,
private_stream_t *this, char *format, va_list ap) private_stream_t *this)
{ {
if (!this->file) FILE *file;
int fd;
/* fclose() closes the FD passed to fdopen(), so dup() it */
fd = dup(this->fd);
if (fd == -1)
{ {
this->file = fdopen(this->fd, "w+"); return NULL;
if (!this->file)
{
return -1;
}
} }
return vfprintf(this->file, format, ap); file = fdopen(fd, "w+");
} if (!file)
{
METHOD(stream_t, print, int, close(fd);
private_stream_t *this, char *format, ...) }
{ return file;
va_list ap;
int ret;
va_start(ap, format);
ret = vprint(this, format, ap);
va_end(ap);
return ret;
} }
METHOD(stream_t, destroy, void, METHOD(stream_t, destroy, void,
private_stream_t *this) private_stream_t *this)
{ {
remove_watcher(this); remove_watcher(this);
if (this->file) close(this->fd);
{
fclose(this->file);
}
else
{
close(this->fd);
}
free(this); free(this);
} }
@@ -258,8 +239,7 @@ stream_t *stream_create_from_fd(int fd)
.on_read = _on_read, .on_read = _on_read,
.write = _write_, .write = _write_,
.on_write = _on_write, .on_write = _on_write,
.print = _print, .get_file = _get_file,
.vprint = _vprint,
.destroy = _destroy, .destroy = _destroy,
}, },
.fd = fd, .fd = fd,
+3 -14
View File
@@ -101,22 +101,11 @@ struct stream_t {
void (*on_write)(stream_t *this, stream_cb_t cb, void *data); void (*on_write)(stream_t *this, stream_cb_t cb, void *data);
/** /**
* printf() convenience function for this stream. * Get a FILE reference for this stream.
* *
* @param format printf format string * @return FILE*, must be fclose()d, NULL on error
* @param ... argument list for format string
* @return number of characters written, negative on error
*/ */
int (*print)(stream_t *this, char *format, ...); FILE* (*get_file)(stream_t *this);
/**
* vprintf() convenience function for this stream.
*
* @param format printf format string
* @param ap argument list for format string
* @return number of characters written, negative on error
*/
int (*vprint)(stream_t *this, char *format, va_list ap);
/** /**
* Destroy a stream_t. * Destroy a stream_t.