micro-utils/coreutils/chgrp.c

114 lines
2.0 KiB
C
Raw Normal View History

2023-11-06 18:32:22 +03:00
#include <grp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include "make_path.h"
#include "get_stat.h"
int (*get_stat)(const char *prog_name, const char *path, struct stat *stat_path);
unsigned int r_flag;
unsigned int s_flag;
struct group *grp;
int change(const char *file) {
struct stat stat_path;
if (mu_get_stat("chgrp", file, &stat_path))
return 1;
if (lchown(file, stat_path.st_uid, grp->gr_gid)) {
if (!s_flag)
fprintf(stderr, "chgrp: %s: %s\n", file, strerror(errno));
return 1;
}
return 0;
}
int chtree(const char *dst) {
int ret = change(dst);
struct stat stat_path;
if (get_stat("chgrp", dst, &stat_path))
return 1;
if (!S_ISDIR(stat_path.st_mode) || !r_flag)
return ret;
DIR *dir = opendir(dst);
if (dir == NULL) {
if (!s_flag)
fprintf(stderr, "chgrp: %s: Can`t open directory\n", dst);
return 1;
}
struct dirent *ep;
while ((ep = readdir(dir)) != NULL) {
if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
continue;
char *full_path = mu_make_path("chgrp", dst, ep->d_name);
if (full_path == NULL)
continue;
if (chtree(full_path))
ret = 1;
free(full_path);
}
closedir(dir);
return ret;
}
int main(int argc, char **argv) {
int i;
get_stat = mu_get_lstat;
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-')
break;
else if (!strcmp(argv[i], "-r"))
r_flag = 1;
else if (!strcmp(argv[i], "-s") || !strcmp(argv[i], "-f"))
s_flag = 1;
else if (!strcmp(argv[i], "-H"))
get_stat = mu_get_stat;
else if (!strcmp(argv[i], "--help")) {
printf("chgrp [-H if a command line argument is a symbolic link] [-r recursive] [-s silent] [group] [file1 file2...]\n");
return 0;
}
}
if (argc - i < 2) {
fprintf(stderr, "chgrp: missing operand\n");
return 1;
}
grp = getgrnam(argv[i]);
if (!grp) {
fprintf(stderr, "chgrp: unknow group\n");
return 1;
}
argv++;
argc--;
int ret = 0;
for (; i < argc; i++)
if (chtree(argv[i]))
ret = 1;
return ret;
}