util-lib: add easy helpers for temporary directories that rmdir()ed via _cleanup_
This adds mkdtemp_malloc() that is a combination of mkdtemp() plus strdup(). It initializes its return paremeter only if the temporary directory could be created successfully, so that the parameter is exactly non-NULL when the directory exists. rmdir_and_free() and rmdir_and_freep() are also added, and the latter may be used inside of _cleanup_ for such a directory string variable, to automatically rmdir() the directory if it is non-NULL when the scope exits. rmdir_and_free() is similar to the existing rm_rf_and_free() however, is only removes a single directory and does not operate recursively.
This commit is contained in:
@@ -1409,3 +1409,22 @@ int read_nul_string(FILE *f, char **ret) {
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int mkdtemp_malloc(const char *template, char **ret) {
|
||||
char *p;
|
||||
|
||||
assert(template);
|
||||
assert(ret);
|
||||
|
||||
p = strdup(template);
|
||||
if (!p)
|
||||
return -ENOMEM;
|
||||
|
||||
if (!mkdtemp(p)) {
|
||||
free(p);
|
||||
return -errno;
|
||||
}
|
||||
|
||||
*ret = p;
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user