Simplify code and don't use ftw() for chgrp(1)

Fix issue with uninitialized struct stat buffer as well.
This commit is contained in:
sin 2013-10-08 00:45:25 +01:00
parent 8cd24f0525
commit 9eb15ff232

40
chgrp.c
View File

@ -1,16 +1,18 @@
/* See LICENSE file for copyright and license details. */ /* See LICENSE file for copyright and license details. */
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <grp.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <unistd.h>
#include <ftw.h>
#include <errno.h>
#include <grp.h>
#include <sys/types.h>
#include "util.h" #include "util.h"
static int gid; static int gid;
static int failures = 0; static int failures = 0;
static int rflag = 0;
static struct stat st;
static void static void
usage(void) usage(void)
@ -18,25 +20,21 @@ usage(void)
eprintf("usage: chgrp [-R] groupname file...\n"); eprintf("usage: chgrp [-R] groupname file...\n");
} }
static int static void
chgrp(const char *path, const struct stat *st, int f) chgrp(const char *path)
{ {
(void)f; if(chown(path, st.st_uid, gid) == -1) {
if(chown(path, st->st_uid, gid) == -1) {
fprintf(stderr, "chgrp: '%s': %s\n", path, strerror(errno)); fprintf(stderr, "chgrp: '%s': %s\n", path, strerror(errno));
failures++; failures++;
} }
if (rflag)
return 0; recurse(path, chgrp);
} }
int int
main(int argc, char **argv) main(int argc, char **argv)
{ {
int rflag = 0;
struct group *gr; struct group *gr;
struct stat st;
ARGBEGIN { ARGBEGIN {
case 'R': case 'R':
@ -45,20 +43,18 @@ main(int argc, char **argv)
default: default:
usage(); usage();
} ARGEND; } ARGEND;
if(argc < 2) if(argc < 2)
usage(); usage();
errno = 0;
gr = getgrnam(argv[0]); gr = getgrnam(argv[0]);
if(!gr) if (errno)
eprintf("getgrnam %s:");
else if(!gr)
eprintf("chgrp: '%s': No such group\n", argv[0]); eprintf("chgrp: '%s': No such group\n", argv[0]);
gid = gr->gr_gid; gid = gr->gr_gid;
if(rflag) {
while(*++argv)
ftw(*argv, chgrp, FOPEN_MAX);
return EXIT_SUCCESS;
}
while(*++argv) { while(*++argv) {
if(stat(*argv, &st) == -1) { if(stat(*argv, &st) == -1) {
fprintf(stderr, "chgrp: '%s': %s\n", *argv, fprintf(stderr, "chgrp: '%s': %s\n", *argv,
@ -66,7 +62,7 @@ main(int argc, char **argv)
failures++; failures++;
continue; continue;
} }
chgrp(*argv, &st, 0); chgrp(*argv);
} }
return failures; return failures;