util: add new write_string_filef() helper

This new helper combines asprintf() and write_string_file() in one,
which is useful at various places to shorten the code a bit.
This commit is contained in:
Lennart Poettering
2018-06-06 14:39:15 +02:00
parent 9264cc39ce
commit 3130fca5a7
4 changed files with 30 additions and 22 deletions
+4 -12
View File
@@ -228,10 +228,10 @@ finish:
}
static int drop_from_file(const char *fn, uint64_t keep) {
int r, k;
uint32_t hi, lo;
_cleanup_free_ char *p = NULL;
uint64_t current, after;
char *p;
uint32_t hi, lo;
int r, k;
r = read_one_line_file(fn, &p);
if (r < 0)
@@ -241,8 +241,6 @@ static int drop_from_file(const char *fn, uint64_t keep) {
assert_cc(sizeof(lo) == sizeof(unsigned));
k = sscanf(p, "%u %u", &lo, &hi);
free(p);
if (k != 2)
return -EIO;
@@ -255,13 +253,7 @@ static int drop_from_file(const char *fn, uint64_t keep) {
lo = (unsigned) (after & 0xFFFFFFFFULL);
hi = (unsigned) ((after >> 32ULL) & 0xFFFFFFFFULL);
if (asprintf(&p, "%u %u", lo, hi) < 0)
return -ENOMEM;
r = write_string_file(fn, p, WRITE_STRING_FILE_CREATE);
free(p);
return r;
return write_string_filef(fn, WRITE_STRING_FILE_CREATE, "%u %u", lo, hi);
}
int capability_bounding_set_drop_usermode(uint64_t keep) {
+19
View File
@@ -206,6 +206,25 @@ fail:
return 0;
}
int write_string_filef(
const char *fn,
WriteStringFileFlags flags,
const char *format, ...) {
_cleanup_free_ char *p = NULL;
va_list ap;
int r;
va_start(ap, format);
r = vasprintf(&p, format, ap);
va_end(ap);
if (r < 0)
return -ENOMEM;
return write_string_file(fn, p, flags);
}
int read_one_line_file(const char *fn, char **line) {
_cleanup_fclose_ FILE *f = NULL;
int r;
+2
View File
@@ -39,6 +39,8 @@ static inline int write_string_file(const char *fn, const char *line, WriteStrin
return write_string_file_ts(fn, line, flags, NULL);
}
int write_string_filef(const char *fn, WriteStringFileFlags flags, const char *format, ...) _printf_(3, 4);
int read_one_line_file(const char *fn, char **line);
int read_full_file(const char *fn, char **contents, size_t *size);
int read_full_stream(FILE *f, char **contents, size_t *size);