]> git.ipfire.org Git - thirdparty/dovecot/core.git/commitdiff
lib: ostream - Add o_stream_create_file
authorAki Tuomi <aki.tuomi@open-xchange.com>
Sat, 8 Feb 2020 19:56:21 +0000 (21:56 +0200)
committeraki.tuomi <aki.tuomi@open-xchange.com>
Thu, 20 Feb 2020 11:19:56 +0000 (11:19 +0000)
Opens file for reading, and creates it, if it exists.

src/lib/ostream-file.c
src/lib/ostream.h

index e3a85e2b4fdd770d244ec42aa1485b1182323944..869a670ddcfb7778bc174cfb936caecfb1c4cba8 100644 (file)
@@ -16,6 +16,7 @@
 #ifdef HAVE_SYS_UIO_H
 #  include <sys/uio.h>
 #endif
+#include <fcntl.h>
 
 /* 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);
+}
index 25a09cc55e0eb3ea6f0217fb1366cc2d1569d1e8..277cbe1503a7889b23bfa5e9bc3d2c138f4d2912 100644 (file)
@@ -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. */