X-Git-Url: http://git.thejh.net/?p=libjh.git;a=blobdiff_plain;f=io.c;h=a0c2ec2b0ef6385fc6ff66d0c01d0de6de1c5f9c;hp=2173478513a88ae9e6e3ad8726963311d39222bf;hb=21d81f63cedece26286cb46e84f7ebbeed22a7dc;hpb=9e73c19b7eb834507b9e62cb84b07ca53ad7a914 diff --git a/io.c b/io.c index 2173478..a0c2ec2 100644 --- a/io.c +++ b/io.c @@ -1,15 +1,13 @@ // Copyright (2013) Jann Horn -// This code is licensed under the AGPLv3. HEADER #include #include #include #include -#include +HEADER #include #include #include #include -#include #include // Wrapper for `read` that retries on partial reads. @@ -43,7 +41,8 @@ PUBLIC_FN ssize_t read_nointr(int fd, void *buf, size_t count, int *last_res) { // - -1: error // - 0: stream ended // - 1: no problems occured -PUBLIC_FN ssize_t write_nointr(int fd, void *buf, size_t count, int *last_res) { +PUBLIC_FN ssize_t write_nointr(int fd, const void *buf, ssize_t count, int *last_res) { + if (count == -1) count = strlen(buf); errno = 0; size_t done = 0; while (done < count) { @@ -181,3 +180,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; +}