From 467866fd55129d1149200c44849c08e9f71f33a7 Mon Sep 17 00:00:00 2001 From: Jann Horn Date: Fri, 15 Nov 2013 19:17:38 +0100 Subject: [PATCH] add fopen_bistream and fnetopen --- io.c | 36 +++++++++++++++++++++++++++++++++++- net.c | 8 ++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/io.c b/io.c index 17ea4d6..ef1f912 100644 --- a/io.c +++ b/io.c @@ -4,7 +4,7 @@ HEADER #include #include #include #include -#include +HEADER #include #include #include #include @@ -181,3 +181,37 @@ PUBLIC_FN void *mmap_file(void *addr, size_t length, int prot, int flags, char * errno = errno_; return (r==MAP_FAILED) ? NULL : r; } + +// on error, fd remains unchanged, no matter whether you specified "keep" or not +HEADER #define JH_OBS_KEEPFD 1 +HEADER #define JH_OBS_BUFFER 2 +PUBLIC_FN int fopen_bistream(FILE **in, FILE **out, int fd, int flags) { + // check input + if (fd < 0) goto err_out; + bool keep = flags & JH_OBS_KEEPFD; + bool buffer = flags & JH_OBS_BUFFER; + + // create input FILE* + int in_fd = dup(fd); + if (in_fd < 0) goto err_out; + *in = fdopen(in_fd, "r"); + if (!*in) { close(in_fd); goto err_out; } + + // create output FILE* + int out_fd = keep ? dup(fd) : fd; + if (out_fd < 0) goto err_dup_out; + *out = fdopen(out_fd, "w"); + if (!*out) { if (keep) close(out_fd); goto err_dup_out; } + + // avoid buffering data unless the caller really wants it + if (!buffer) setbuf(*out, NULL); + + // success! + return 0; + + +err_dup_out: + fclose(*in); +err_out: + return EAI_SYSTEM; +} \ No newline at end of file diff --git a/net.c b/net.c index d9b2d43..2fba39a 100644 --- a/net.c +++ b/net.c @@ -39,3 +39,11 @@ err_socket: freeaddrinfo(addrs); return EAI_SYSTEM; } + +PUBLIC_FN int fnetopen(FILE **in, FILE **out, const char *node, const char *service, const struct addrinfo *hints) { + int fd = netopen(node, service, hints); + if (fd < 0) return EAI_SYSTEM; + int ret = fopen_bistream(in, out, fd, 0); + if (ret) close(fd); + return ret; +} \ No newline at end of file -- 2.20.1