libremail: file: Add try_touch() function
The try_touch() function is responsible for attempting to create new files while optionally filling it with initial data Signed-off-by: Chloe M. <chloe@mirocom.org>
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* Copyright (c) 2026, Chloe Moffett
|
||||
* Provided under the BSD-3 clause
|
||||
*/
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
#include "libremail/file.h"
|
||||
|
||||
int
|
||||
try_mkdir(const char *path, mode_t mode)
|
||||
{
|
||||
if (path == NULL) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (access(path, F_OK) != 0) {
|
||||
return mkdir(path, mode);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
try_touch(const char *path, mode_t mode, void *buf, size_t len)
|
||||
{
|
||||
ssize_t retlen;
|
||||
int fd;
|
||||
|
||||
if (path == NULL) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
|
||||
fd = open(path, O_RDONLY | O_CREAT, mode);
|
||||
if (fd < 0) {
|
||||
perror("open");
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Write the initial contents if we can */
|
||||
if (buf != NULL) {
|
||||
retlen = write(fd, buf, len);
|
||||
if (retlen <= 0) {
|
||||
close(fd);
|
||||
perror("write");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user