]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
io-util: add new helper fputs_with_newline()
authorLennart Poettering <lennart@poettering.net>
Thu, 13 Jun 2024 07:29:10 +0000 (09:29 +0200)
committerLennart Poettering <lennart@poettering.net>
Thu, 13 Jun 2024 07:33:13 +0000 (09:33 +0200)
src/basic/io-util.c
src/basic/io-util.h
src/core/unit.c

index 6bcbef3413623dd624ff0f98c44fe952cffbecf5..e07e1a1e1911fb295c3b9c7f1188ebbe06e53135 100644 (file)
@@ -306,3 +306,19 @@ ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
 
         return q - (const uint8_t*) p;
 }
+
+int fputs_with_newline(const char *s, FILE *f) {
+        assert(s);
+        assert(f);
+
+        /* This is like fputs() but outputs a trailing newline char, but only if the string doesn't end in a
+         * newline anyway. Just like fputs() returns EOF on error. Otherwise returns 0 in case we didn't
+         * append a newline, > 0 otherwise. */
+
+        if (fputs(s, f) == EOF)
+                return EOF;
+        if (endswith(s, "\n"))
+                return 0;
+
+        return fputc('\n', f) == EOF ? EOF : 1;
+}
index e027c1a878ccd80f5cb0b2d412ce1811ed3aae3a..0d9007a304d7144370f9c2a086723f7d6988ad52 100644 (file)
@@ -5,6 +5,7 @@
 #include <stdbool.h>
 #include <stddef.h>
 #include <stdint.h>
+#include <stdio.h>
 #include <sys/types.h>
 
 #include "macro.h"
@@ -44,3 +45,5 @@ static inline bool FILE_SIZE_VALID_OR_INFINITY(uint64_t l) {
         return FILE_SIZE_VALID(l);
 
 }
+
+int fputs_with_newline(const char *s, FILE *f);
index 35e790ebba552b46cf1ed95897d08a86f853557c..99c1db3a1a682e527f12d47179f6c49ba1355e7e 100644 (file)
@@ -33,6 +33,7 @@
 #include "format-util.h"
 #include "id128-util.h"
 #include "install.h"
+#include "io-util.h"
 #include "iovec-util.h"
 #include "label-util.h"
 #include "load-dropin.h"
@@ -4569,10 +4570,7 @@ int unit_write_setting(Unit *u, UnitWriteFlags flags, const char *name, const ch
         if (u->transient_file) {
                 /* When this is a transient unit file in creation, then let's not create a new drop-in but instead
                  * write to the transient unit file. */
-                fputs(data, u->transient_file);
-
-                if (!endswith(data, "\n"))
-                        fputc('\n', u->transient_file);
+                fputs_with_newline(data, u->transient_file);
 
                 /* Remember which section we wrote this entry to */
                 u->last_section_private = !!(flags & UNIT_PRIVATE);