From: Aki Tuomi Date: Sat, 8 Feb 2020 19:56:21 +0000 (+0200) Subject: lib: ostream - Add o_stream_create_file X-Git-Tag: 2.3.11.2~596 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=b2dca5344fbc9c334238362e0785a6168f07ac49;p=thirdparty%2Fdovecot%2Fcore.git lib: ostream - Add o_stream_create_file Opens file for reading, and creates it, if it exists. --- diff --git a/src/lib/ostream-file.c b/src/lib/ostream-file.c index e3a85e2b4f..869a670ddc 100644 --- a/src/lib/ostream-file.c +++ b/src/lib/ostream-file.c @@ -16,6 +16,7 @@ #ifdef HAVE_SYS_UIO_H # include #endif +#include /* try to keep the buffer size within 4k..128k. ReiserFS may actually return 128k as optimal size. */ @@ -1117,3 +1118,17 @@ struct ostream *o_stream_create_fd_file_autoclose(int *fd, uoff_t offset) *fd = -1; return output; } + +struct ostream *o_stream_create_file(const char *path, uoff_t offset, mode_t mode, + enum ostream_create_file_flags flags) +{ + int fd; + int open_flags = O_WRONLY|O_CREAT; + if (HAS_ANY_BITS(flags, OSTREAM_CREATE_FILE_FLAG_APPEND)) + open_flags |= O_APPEND; + else + open_flags |= O_TRUNC; + if ((fd = open(path, open_flags, mode)) < 0) + return o_stream_create_error(errno); + return o_stream_create_fd_file_autoclose(&fd, offset); +} diff --git a/src/lib/ostream.h b/src/lib/ostream.h index 25a09cc55e..277cbe1503 100644 --- a/src/lib/ostream.h +++ b/src/lib/ostream.h @@ -17,6 +17,11 @@ enum ostream_send_istream_result { OSTREAM_SEND_ISTREAM_RESULT_ERROR_OUTPUT }; +enum ostream_create_file_flags { + /* without append, file is truncated */ + OSTREAM_CREATE_FILE_FLAG_APPEND = BIT(0), +}; + struct ostream { /* Number of bytes sent via o_stream_send*() and similar functions. This is counting the input data. For example with a compressed @@ -59,6 +64,9 @@ struct ostream *o_stream_create_fd_autoclose(int *fd, size_t max_buffer_size); struct ostream * o_stream_create_fd_file(int fd, uoff_t offset, bool autoclose_fd); struct ostream *o_stream_create_fd_file_autoclose(int *fd, uoff_t offset); +/* Create ostream for file. If append flag is not set, file will be truncated. */ +struct ostream *o_stream_create_file(const char *path, uoff_t offset, mode_t mode, + enum ostream_create_file_flags flags); /* Create an output stream to a buffer. */ struct ostream *o_stream_create_buffer(buffer_t *buf); /* Create an output streams that always fails the writes. */