fileio: add 'enforce_newline' argument to write_string_stream()

Add a flag to control whether write_string_stream() should always enforce a
trailing newline character in the file.
This commit is contained in:
Daniel Mack 2015-07-06 17:31:44 -04:00
parent eff8efe671
commit 40beecdb6d
4 changed files with 19 additions and 9 deletions

View file

@ -27,14 +27,14 @@
#include "ctype.h"
#include "fileio.h"
int write_string_stream(FILE *f, const char *line) {
int write_string_stream(FILE *f, const char *line, bool enforce_newline) {
assert(f);
assert(line);
errno = 0;
fputs(line, f);
if (!endswith(line, "\n"))
if (enforce_newline && !endswith(line, "\n"))
fputc('\n', f);
fflush(f);
@ -55,7 +55,7 @@ int write_string_file(const char *fn, const char *line) {
if (!f)
return -errno;
return write_string_stream(f, line);
return write_string_stream(f, line, true);
}
int write_string_file_no_create(const char *fn, const char *line) {
@ -77,7 +77,7 @@ int write_string_file_no_create(const char *fn, const char *line) {
return -errno;
}
return write_string_stream(f, line);
return write_string_stream(f, line, true);
}
int write_string_file_atomic(const char *fn, const char *line) {
@ -94,7 +94,7 @@ int write_string_file_atomic(const char *fn, const char *line) {
fchmod_umask(fileno(f), 0644);
r = write_string_stream(f, line);
r = write_string_stream(f, line, true);
if (r >= 0) {
if (rename(p, fn) < 0)
r = -errno;

View file

@ -25,7 +25,7 @@
#include "macro.h"
int write_string_stream(FILE *f, const char *line);
int write_string_stream(FILE *f, const char *line, bool enforce_newline);
int write_string_file(const char *fn, const char *line);
int write_string_file_no_create(const char *fn, const char *line);
int write_string_file_atomic(const char *fn, const char *line);

View file

@ -65,7 +65,7 @@ static int write_state(FILE **f, char **states) {
STRV_FOREACH(state, states) {
int k;
k = write_string_stream(*f, *state);
k = write_string_stream(*f, *state, true);
if (k == 0)
return 0;
log_debug_errno(k, "Failed to write '%s' to /sys/power/state: %m",

View file

@ -302,17 +302,27 @@ static void test_write_string_stream(void) {
f = fdopen(fd, "r");
assert_se(f);
assert_se(write_string_stream(f, "boohoo") < 0);
assert_se(write_string_stream(f, "boohoo", true) < 0);
f = freopen(fn, "r+", f);
assert_se(f);
assert_se(write_string_stream(f, "boohoo") == 0);
assert_se(write_string_stream(f, "boohoo", true) == 0);
rewind(f);
assert_se(fgets(buf, sizeof(buf), f));
assert_se(streq(buf, "boohoo\n"));
f = freopen(fn, "w+", f);
assert_se(f);
assert_se(write_string_stream(f, "boohoo", false) == 0);
rewind(f);
assert_se(fgets(buf, sizeof(buf), f));
printf(">%s<", buf);
assert_se(streq(buf, "boohoo"));
unlink(fn);
}