Skip to content

Commit 8eea9f5

Browse files
committed
Check if the directory exists and the user has write permission
1 parent 412c991 commit 8eea9f5

1 file changed

Lines changed: 10 additions & 1 deletion

File tree

brightnessctl.c

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ static bool find_devices(struct device **, char *);
6161
static bool save_device_data(struct device *);
6262
static bool restore_device_data(struct device *);
6363
static bool mkdir_parent(const char *);
64+
static bool ensure_dir(const char *);
6465

6566
#ifdef ENABLE_LOGIND
6667
static bool logind_set_brightness(struct device *);
@@ -566,7 +567,7 @@ bool save_device_data(struct device *dev) {
566567
char *c_path = dir_child(run_dir, dev->class);
567568
char *d_path = dir_child(c_path, dev->id);
568569
bool ret = true;
569-
if (mkdir_parent(c_path)) {
570+
if (ensure_dir(c_path)) {
570571
FILE *fp = fopen(d_path, "wb");
571572
if (fp) {
572573
fwrite(&dev->curr_brightness, sizeof(dev->curr_brightness), 1, fp);
@@ -579,6 +580,8 @@ bool save_device_data(struct device *dev) {
579580
ret = false;
580581
fprintf(stderr, "Error opening '%s': %s\n", d_path, strerror(errno));
581582
}
583+
} else {
584+
fprintf(stderr, "Failed to access or create '%s': %s\n", path, strerror(errno));
582585
}
583586
free(c_path);
584587
free(d_path);
@@ -630,6 +633,12 @@ bool mkdir_parent(const char *path) {
630633
return ret;
631634
}
632635

636+
static bool ensure_dir(const char * path) {
637+
if (!access(path, W_OK))
638+
return true;
639+
return errno == ENOENT ? mkdir_parent(path) : false;
640+
}
641+
633642
char *_cat_with(char c, ...) {
634643
size_t size = 32;
635644
size_t length = 0;

0 commit comments

Comments
 (0)