So I am trying to make my own version of chmod using C, the modifications are to make lowercase add permissions while uppercase remove permissions (instead of using + or - to add and remove). Also, I am trying to print a help message and exit if the command cannot be properly parsed, or there is no file specified. In the case I cannot change permissions (like in the instance I am not the user owner of the file) it should mark that file as having an exit status of 2. I have two versions, the first works ok, still needs the part that takes in input and modifies appropreatly. Not only that but it never recognizes the file name. The second is from the original chmod code that I modified, though its not even close to being in C. Help with eather would be greatly appreceated.
first version

#include <stdio.h>
#include <stdlib.h>
int debug = 0;
int main(int argc, char **argv)
{
extern char *optarg; extern int optind;
int c, err = 0;
int mflag=0, pflag=0, fflag=0;
char *sname = "default_sname", *fname;
static char usage[] = "usage: %s [-dmp] -f fname [-s sname] name [name ...]\n";
while ((c = getopt(argc, argv, "df:mps:")) != -1)
switch (c) {
case 'd':
        debug = 1;
        break;
case 'm':
        mflag = 1;
        break;
case 'p':
        pflag = 1;
        break;
case 'f':
        fflag = 1;
        fname = optarg;
        break;
case 's':
        sname = optarg;
        break;
case '?':
        err = 1;
        break;
}
if (fflag == 0) {
        fprintf(stderr, "%s: missing -f option\n", argv[0]);
        fprintf(stderr, usage, argv[0]);
        exit(1);
}
else if ((optind+14) > argc) {
        printf("optind = %d, argc=%d\n", optind, argc);
        fprintf(stderr, "%s: missing name\n", argv[0]);
        fprintf(stderr, usage, argv[0]);
        exit(1);
}
else if (err) {
        fprintf(stderr, usage, argv[0]);
        exit(1);
}
printf("debug = %d\n", debug);
printf("pflag = %d\n", pflag);
printf("mflag = %d\n", mflag);
printf("fname = \"%s\"\n", fname);
printf("sname = \"%s\"\n", sname);
if (optind < argc)
        for (; optind < argc; optind++)
                printf("argument: \"%s\"\n", argv[optind]);
else { printf("no arguments left to process\n");
}
while (argv[optind] != NULL){
if (argv[optind] == "-o"){
        exit(0);
}
else{
argv[optind+1];
}
}
exit(2);
}

second version

#include <config.h>
#include <stdio.h>
#include <getopt.h>
#include <sys/types.h>
#include "system.h"
#include "dev-ino.h"
#include "error.h"
#include "filemode.h"
#include "ignore-value.h"
#include "modechange.h"
#include "quote.h"
#include "quotearg.h"
#include "root-dev-ino.h"
#include "xfts.h"
#define PROGRAM_NAME "mychmod"
enum Change_status
{
  CH_NOT_APPLIED,
  CH_SUCCEEDED,
  CH_FAILED,
  CH_NO_CHANGE_REQUESTED
};
enum Verbosity
{
  /* Print a message for each file that is processed.  */
  V_high,
  /* Print a message for each file whose attributes we change.  */
  V_changes_only,
  /* Do not be verbose.  This is the default. */
  V_off
};
/* The desired change to the mode.  */
static struct mode_change *change;
/* The initial umask value, if it might be needed.  */
static mode_t umask_value;
/* If true, change the modes of directories recursively. */
static bool recurse;
/* If true, force silence (suppress most of error messages). */
static bool force_silent;
/* If true, diagnose surprises from naive misuses like "mychmod -r file".
   POSIX allows diagnostics here, as portable code is supposed to use
   "mychmod -- -r file".  */
static bool diagnose_surprises;
/* Level of verbosity.  */
static enum Verbosity verbosity = V_off;
/* Pointer to the device and inode numbers of '/', when --recursive.
   Otherwise NULL.  */
static struct dev_ino *root_dev_ino;
/* For long options that have no equivalent short option, use a
   non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
enum
{
  NO_PRESERVE_ROOT = CHAR_MAX + 1,
  PRESERVE_ROOT,
  REFERENCE_FILE_OPTION
};
static struct option const long_options[] =
{
  {"changes", no_argument, NULL, 'c'},
  {"recursive", no_argument, NULL, 'R'},
  {"no-preserve-root", no_argument, NULL, NO_PRESERVE_ROOT},
  {"preserve-root", no_argument, NULL, PRESERVE_ROOT},
  {"quiet", no_argument, NULL, 'f'},
  {"reference", required_argument, NULL, REFERENCE_FILE_OPTION},
  {"silent", no_argument, NULL, 'f'},
  {"verbose", no_argument, NULL, 'v'},
  {GETOPT_HELP_OPTION_DECL},
  {GETOPT_VERSION_OPTION_DECL},
  {NULL, 0, NULL, 0}
};
/* Return true if the mychmodable permission bits of FILE changed.
   The old mode was OLD_MODE, but it was changed to NEW_MODE.  */
static bool
mode_changed (int dir_fd, char const *file, char const *file_full_name,
              mode_t old_mode, mode_t new_mode)
{
  if (new_mode & (S_ISUID | S_ISGID | S_ISVTX))
    {
      /* The new mode contains unusual bits that the call to mychmod may
         have silently cleared.  Check whether they actually changed.  */
      struct stat new_stats;
      if (fstatat (dir_fd, file, &new_stats, 0) != 0)
        {
          if (! force_silent)
            error (0, errno, _("getting new attributes of %s"),
                   quote (file_full_name));
          return false;
        }
      new_mode = new_stats.st_mode;
    }
  return ((old_mode ^ new_mode) & MYCHMOD_MODE_BITS) != 0;
}
/* Tell the user how/if the MODE of FILE has been changed.
   CHANGED describes what (if anything) has happened. */
static void
describe_change (const char *file, mode_t old_mode, mode_t mode,
                 enum Change_status changed)
{
  char perms[12];               /* "-rwxrwxrwx" ls-style modes. */
  char old_perms[12];
  const char *fmt;
  if (changed == CH_NOT_APPLIED)
    {
      printf (_("neither symbolic link %s nor referent has been changed\n"),
              quote (file));
      return;
    }
  strmode (mode, perms);
  perms[10] = '\0';             /* Remove trailing space.  */
  strmode (old_mode, old_perms);
  old_perms[10] = '\0';         /* Remove trailing space.  */
  switch (changed)
    {
    case CH_SUCCEEDED:
      fmt = _("mode of %s changed from %04lo (%s) to %04lo (%s)\n");
      break;
    case CH_FAILED:
      fmt = _("failed to change mode of %s from %04lo (%s) to %04lo (%s)\n");
      break;
    case CH_NO_CHANGE_REQUESTED:
      fmt = _("mode of %s retained as %04lo (%s)\n");
      printf (fmt, quote (file),
              (unsigned long int) (mode & CHMOD_MODE_BITS), &perms[1]);
      return;
    default:
      abort ();
    }
  printf (fmt, quote (file),
          (unsigned long int) (old_mode & CHMOD_MODE_BITS), &old_perms[1],
          (unsigned long int) (mode & CHMOD_MODE_BITS), &perms[1]);
}
/* Change the mode of FILE.
   Return true if successful.  This function is called
   once for every file system object that fts encounters.  */
static bool
process_file (FTS *fts, FTSENT *ent)
{
  char const *file_full_name = ent->fts_path;
  char const *file = ent->fts_accpath;
  const struct stat *file_stats = ent->fts_statp;
  mode_t old_mode IF_LINT ( = 0);
  mode_t new_mode IF_LINT ( = 0);
  bool ok = true;
  bool mychmod_succeeded = false;
  switch (ent->fts_info)
    {
    case FTS_DP:
      return true;
    case FTS_NS:
      /* For a top-level file or directory, this FTS_NS (stat failed)
         indicator is determined at the time of the initial fts_open call.
         With programs like mychmod, chown, and chgrp, that modify
         permissions, it is possible that the file in question is
         accessible when control reaches this point.  So, if this is
         the first time we've seen the FTS_NS for this file, tell
         fts_read to stat it "again".  */
      if (ent->fts_level == 0 && ent->fts_number == 0)
        {
          ent->fts_number = 1;
          fts_set (fts, ent, FTS_AGAIN);
          return true;
        }
      if (! force_silent)
        error (0, ent->fts_errno, _("cannot access %s"),
               quote (file_full_name));
      ok = false;
      break;
    case FTS_ERR:
      if (! force_silent)
        error (0, ent->fts_errno, "%s", quote (file_full_name));
      ok = false;
      break;
    case FTS_DNR:
      if (! force_silent)
        error (0, ent->fts_errno, _("cannot read directory %s"),
               quote (file_full_name));
      ok = false;
      break;
    case FTS_SLNONE:
      if (! force_silent)
        error (0, 0, _("cannot operate on dangling symlink %s"),
               quote (file_full_name));
      ok = false;
      break;
    case FTS_DC:                /* directory that causes cycles */
      if (cycle_warning_required (fts, ent))
        {
          emit_cycle_warning (file_full_name);
          return false;
        }
      break;
    default:
      break;
    }
  if (ok && ROOT_DEV_INO_CHECK (root_dev_ino, file_stats))
    {
      ROOT_DEV_INO_WARN (file_full_name);
      /* Tell fts not to traverse into this hierarchy.  */
      fts_set (fts, ent, FTS_SKIP);
      /* Ensure that we do not process "/" on the second visit.  */
      ignore_value (fts_read (fts));
      return false;
    }
  if (ok)
    {
      old_mode = file_stats->st_mode;
      new_mode = mode_adjust (old_mode, S_ISDIR (old_mode) != 0, umask_value,
                              change, NULL);
      if (! S_ISLNK (old_mode))
        {
          if (chmodat (fts->fts_cwd_fd, file, new_mode) == 0)
            mychmod_succeeded = true;
          else
            {
              if (! force_silent)
                error (0, errno, _("changing permissions of %s"),
                       quote (file_full_name));
              ok = false;
            }
        }
    }
  if (verbosity != V_off)
    {
      bool changed = (mychmod_succeeded
                      && mode_changed (fts->fts_cwd_fd, file, file_full_name,
                                       old_mode, new_mode));
      if (changed || verbosity == V_high)
        {
          enum Change_status ch_status =
            (!ok ? CH_FAILED
             : !mychmod_succeeded ? CH_NOT_APPLIED
             : !changed ? CH_NO_CHANGE_REQUESTED
             : CH_SUCCEEDED);
          describe_change (file_full_name, old_mode, new_mode, ch_status);
        }
    }
  if (mychmod_succeeded && (case == 'U' || case == 'G' || case == 'O'))
    {
      mode_t naively_expected_mode =
        mode_adjust (old_mode, S_ISDIR (old_mode) != 0, 0, change, NULL);
      if (new_mode & ~naively_expected_mode)
        {
          char new_perms[12];
          char naively_expected_perms[12];
          strmode (new_mode, new_perms);
          strmode (naively_expected_mode, naively_expected_perms);
          new_perms[10] = naively_expected_perms[10] = '\0';
          error (0, 0,
                 _("%s: new permissions are %s, not %s"),
                 quotearg_colon (file_full_name),
                 new_perms + 1, naively_expected_perms + 1);
          ok = false;
        }
    }
  if ( ! recurse)
    fts_set (fts, ent, FTS_SKIP);
  return ok;
}
/* Recursively change the modes of the specified FILES (the last entry
   of which is NULL).  BIT_FLAGS controls how fts works.
   Return true if successful.  */
static bool
process_files (char **files, int bit_flags)
{
  bool ok = true;
  FTS *fts = xfts_open (files, bit_flags, NULL);
  while (1)
    {
      FTSENT *ent;
      ent = fts_read (fts);
      if (ent == NULL)
        {
          if (errno != 0)
            {
              /* FIXME: try to give a better message  */
              if (! force_silent)
                error (0, errno, _("fts_read failed"));
              ok = false;
            }
          break;
        }
      ok &= process_file (fts, ent);
    }
  if (fts_close (fts) != 0)
    {
      error (0, errno, _("fts_close failed"));
      ok = false;
    }
  return ok;
}
void
usage (int status)
{
  if (status != EXIT_SUCCESS)
    emit_try_help ();
  else
    {
      printf (_("\
Usage: %s [OPTION]... MODE[,MODE]... FILE...\n\
  or:  %s [OPTION]... OCTAL-MODE FILE...\n\
  or:  %s [OPTION]... --reference=RFILE FILE...\n\
"),
              program_name, program_name, program_name);
      fputs (_("\
Change the mode of each FILE to MODE.\n\
With --reference, change the mode of each FILE to that of RFILE.\n\
\n\
"), stdout);
      fputs (_("\
  -c, --changes          like verbose but report only when a change is made\n\
  -f, --silent, --quiet  suppress most error messages\n\
  -v, --verbose          output a diagnostic for every file processed\n\
"), stdout);
      fputs (_("\
      --no-preserve-root  do not treat '/' specially (the default)\n\
      --preserve-root    fail to operate recursively on '/'\n\
"), stdout);
      fputs (_("\
      --reference=RFILE  use RFILE's mode instead of MODE values\n\
"), stdout);
      fputs (_("\
  -R, --recursive        change files and directories recursively\n\
"), stdout);
      fputs (HELP_OPTION_DESCRIPTION, stdout);
      fputs (VERSION_OPTION_DESCRIPTION, stdout);
      fputs (_("\
\n\
Each MODE is of the form '[ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=][0-7]+'.\n\
"), stdout);
      emit_ancillary_info (PROGRAM_NAME);    }
  exit (status);
}
/* Parse the ASCII mode given on the command line into a linked list
   of 'struct mode_change' and apply that to each file argument. */
int
main (int argc, char **argv)
{
  char *mode = NULL;
  size_t mode_len = 0;
  size_t mode_alloc = 0;
  bool ok;
  bool preserve_root = false;
  char const *reference_file = NULL;
  int c;
  initialize_main (&argc, &argv);
  set_program_name (argv[0]);
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);
  atexit (close_stdout);
  recurse = force_silent = diagnose_surprises = false;
  while ((c = getopt_long (argc, argv,
                           ("Rcfvr::w::x::X::s::t::u::g::o::a::U::G::O::,::+::=::"
                            "0::1::2::3::4::5::6::7::"),
                           long_options, NULL))
         != -1)
    {
      switch (c)
        {
        case 'r':
        case 'w':
        case 'x':
        case 'X':
        case 's':
        case 't':
        case 'u':
        case 'g':
        case 'o':
        case 'a':
        case 'U':
        case 'G':
        case 'O';
        case '':
        case '=':
        case '0': case '1': case '2': case '3':
        case '4': case '5': case '6': case '7':
          /* Support nonportable uses like "mychmod -w", but diagnose
             surprises due to umask confusion.  Even though "--", "--r",
             etc., are valid modes, there is no "case '-'" here since
             getopt_long reserves leading "--" for long options.  */
          {
            /* Allocate a mode string (e.g., "-rwx") by concatenating
               the argument containing this option.  If a previous mode
               string was given, concatenate the previous string, a
               comma, and the new string (e.g., "-s,-rwx").  */
            char const *arg = argv[optind - 1];
            size_t arg_len = strlen (arg);
            size_t mode_comma_len = mode_len + !!mode_len;
            size_t new_mode_len = mode_comma_len + arg_len;
            if (mode_alloc <= new_mode_len)
              {
                mode_alloc = new_mode_len + 1;
                mode = X2REALLOC (mode, &mode_alloc);
              }
            mode[mode_len] = ',';
            memcpy (mode + mode_comma_len, arg, arg_len + 1);
            mode_len = new_mode_len;
            diagnose_surprises = true;
          }
          break;
        case NO_PRESERVE_ROOT:
          preserve_root = false;
          break;
        case PRESERVE_ROOT:
          preserve_root = true;
          break;
        case REFERENCE_FILE_OPTION:
          reference_file = optarg;
          break;
        case 'R':
          recurse = true;
          break;
        case 'c':
          verbosity = V_changes_only;
          break;
        case 'f':
          force_silent = true;
          break;
        case 'v':
          verbosity = V_high;
          break;
        case_GETOPT_HELP_CHAR;
        case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
        default:
          usage (EXIT_FAILURE);
        }
    }
  if (reference_file)
    {
      if (mode)
        {
          error (0, 0, _("cannot combine mode and --reference options"));
          usage (EXIT_FAILURE);
        }
    }
  else
    {
      if (!mode)
        mode = argv[optind++];
    }
  if (optind >= argc)
    {
      if (!mode || mode != argv[optind - 1])
        error (0, 0, _("missing operand"));
      else
        error (0, 0, _("missing operand after %s"), quote (argv[argc - 1]));
      usage (EXIT_FAILURE);
    }
  if (reference_file)
    {
      change = mode_create_from_ref (reference_file);
      if (!change)
        error (EXIT_FAILURE, errno, _("failed to get attributes of %s"),
               quote (reference_file));
    }
  else
    {
      change = mode_compile (mode);
      if (!change)
        {
          error (0, 0, _("invalid mode: %s"), quote (mode));
          usage (EXIT_FAILURE);
        }
      umask_value = umask (0);
    }
  if (recurse && preserve_root)
    {
      static struct dev_ino dev_ino_buf;
      root_dev_ino = get_root_dev_ino (&dev_ino_buf);
      if (root_dev_ino == NULL)
        error (EXIT_FAILURE, errno, _("failed to get attributes of %s"),
               quote ("/"));
    }
  else
    {
      root_dev_ino = NULL;
    }
  ok = process_files (argv + optind,
                      FTS_COMFOLLOW | FTS_PHYSICAL | FTS_DEFER_STAT);
  return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}

Thank you for your time and help in this matter!

so in update I found the chmod code done by apple and have modified it some. I think instead of using the char casts below I should use isUpeer and isLower to check if the input is in upper or lower case. Not sure if that would work the way I think it would. However, the main problem is that now it is saying that the FTP is not declared, along with a lot of other calls. As C does not have <ftp.h> to include I think it may need to be modified more to a getopt format. What do you guys think? Any suggestions on making this code work? Thanks for any and all help!

#ifndef lint
#endif /* not lint */
#ifndef lint
#if 0
static char sccsid[] = "@(#)mychmod.c   8.8 (Ryan) 3/12/15";
#endif
#endif /* not lint */
#include <sys/cdefs.h>
__RCSID("$FreeBSD: src/bin/mychmod/mychmod.c,v 1.27 obrien Exp $");
#include <sys/types.h>
#include <sys/stat.h>
#include <err.h>
#include <errno.h>
#include <fts.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifdef __APPLE__
#include "chmod_acl.h"
#endif
int fflag = 0;
int main(int, char *[]);
void usage(void);
int
main(int argc, char *argv[])
{
    FTS *ftsp = NULL;
    FTSENT *p = NULL;
    mode_t *set = NULL;
    long val = 0;
    int oct = 0;
    int Hflag, Lflag, Pflag, Rflag, ch, fts_options, hflag, rval;
    int vflag;
    char *ep, *mode;
    mode_t newmode, omode;
#ifdef __APPLE__
    unsigned int acloptflags = 0;
    int aclpos = -1, inheritance_level = 0;
    int index = 0, acloptlen = 0, ace_arg_not_required = 0;
    acl_t acl_input = NULL;
#endif /* __APPLE__*/
    int (*change_mode)(const char *, mode_t);

    set = NULL;
    omode = 0;
    Hflag = Lflag = Pflag = Rflag = fflag = hflag = vflag = 0;
#ifndef __APPLE__
    while ((ch = getopt(argc, argv, "HLPRXfghorstuvwx")) != -1)
#else
    while ((ch = getopt(argc, argv, "ACEHILNPRVXafghinorstuvwx")) != -1)
#endif
        switch (ch) {
        case 'H':
            Hflag = 1;
            Lflag = 0;
            Pflag = 0;
            break;
        case 'L':
            Lflag = 1;
            Hflag = 0;
            Pflag = 0;
            break;
        case 'P':
            Hflag = Lflag = 0;
            Pflag = 1;
            break;
        case 'R':
            Rflag = 1;
            break;
        case 'f':
            fflag = 1;
            break;
        case 'h':
            /*
             * In System V (and probably POSIX.2) the -h option
             * causes chmod to change the mode of the symbolic
             * link.  4.4BSD's symbolic links didn't have modes,
             * so it was an undocumented noop.  In FreeBSD 3.0,
             * lchmod(2) is introduced and this option does real
             * work.
             */
            hflag = 1;
            break;
#ifdef __APPLE__
        case 'a':
            if (argv[optind - 1][0] == '-' &&
                argv[optind - 1][1] == ch)
                --optind;
            goto done;
        case 'A':
            acloptflags |= ACL_FLAG | ACL_TO_STDOUT;
            ace_arg_not_required = 1;
            errx(1, "-A not implemented");
            goto done;
        case 'E':
            acloptflags |= ACL_FLAG | ACL_FROM_STDIN;
            goto done;
        case 'C':
            acloptflags |= ACL_FLAG | ACL_CHECK_CANONICITY;
            ace_arg_not_required = 1;
            goto done;
        case 'i':
            acloptflags |= ACL_FLAG | ACL_REMOVE_INHERIT_FLAG;
            ace_arg_not_required = 1;
            goto done;
        case 'I':
            acloptflags |= ACL_FLAG | ACL_REMOVE_INHERITED_ENTRIES;
            ace_arg_not_required = 1;
            goto done;
        case 'n':
            acloptflags |= ACL_FLAG | ACL_NO_TRANSLATE;
            break;
        case 'N':
            acloptflags |= ACL_FLAG | ACL_CLEAR_FLAG;
            ace_arg_not_required = 1;
            goto done;
        case 'V':
            acloptflags |= ACL_FLAG | ACL_INVOKE_EDITOR;
            ace_arg_not_required = 1;
            errx(1, "-V not implemented");
            goto done;
#endif
        /*
         * XXX
         * "-[rwx]" are valid mode commands.  If they are the entire
         * argument, getopt has moved past them, so decrement optind.
         * Regardless, we're done argument processing.
         */
        case 'g': case 'o': case 'r': case 's': case 'S':
        case 'U': case 'G': case 'O': case 'T': case 'U':
        case 't': case 'u': case 'w': case 'X': case 'x':
            if (argv[optind - 1][0] == '-' &&
                argv[optind - 1][1] == ch &&
                argv[optind - 1][2] == '\0')
                --optind;
            goto done;
        case 'v':
            vflag++;
            break;
        case '?':
        default:
            usage();
        }
done:   argv += optind;
    argc -= optind;

#ifdef __APPLE__
    if (argc < ((acloptflags & ACL_FLAG) ? 1 : 2))
        usage();
    if (!Rflag && (Hflag || Lflag || Pflag))
        warnx("options -H, -L, -P only useful with -R");
#else
    if (argc < 2)
        usage();
#endif

#ifdef __APPLE__
    if (!(acloptflags & ACL_FLAG) && ((acloptlen = strlen(argv[0])) > 1) && (argv[0][1] == 'a')) {
        acloptflags |= ACL_FLAG;
        switch (argv[0][0]) {
        case 'u': case 'g': case 'o': case 'u': case 'x': case 't': case 's':
            acloptflags |= ACL_SET_FLAG;
            break;
        case 'U': case 'G': case 'O': case 'U': case 'X': case 'T': case 'S':
            acloptflags |= ACL_DELETE_FLAG;
            break;
        case '=':
            acloptflags |= ACL_REWRITE_FLAG;
            break;
        default:
            acloptflags &= ~ACL_FLAG;
            goto apnoacl;
        }

        if (argc < 3)
            usage();
        if (acloptlen > 2) {
            for (index = 2; index < acloptlen; index++) {
                switch (argv[0][index]) {
                case '#':
                    acloptflags |= ACL_ORDER_FLAG;
                    if (argc < ((acloptflags & ACL_DELETE_FLAG)
                            ? 3 : 4))
                        usage();
                    argv++;
                    argc--;
                    errno = 0;
                    aclpos = strtol(argv[0], &ep, 0);

                    if (aclpos > ACL_MAX_ENTRIES
                        || aclpos < 0)
                        errno = ERANGE;
                    if (errno || *ep)
                        errx(1, "Invalid ACL entry number: %d", aclpos);
                    if (acloptflags & ACL_DELETE_FLAG)
                        ace_arg_not_required = 1;
                    goto apdone;
                case 'i':
                    acloptflags |= ACL_INHERIT_FLAG;
                    /* The +aii.. syntax to specify
                     * inheritance level is rather unwieldy,
                     * find an alternative.
                     */
                    inheritance_level++;
                    if (inheritance_level > 1)
                        warnx("Inheritance across more than one generation is not currently supported");
                    if (inheritance_level >= MAX_INHERITANCE_LEVEL)
                        goto apdone;
                    break;
                default:
                    errno = EINVAL;
                    usage();
                }
            }
        }
apdone:
        argv++;
        argc--;
    }
apnoacl:
#endif
    if (Rflag) {
        fts_options = FTS_PHYSICAL;
        if (hflag)
            errx(1,
        "the -R and -h options may not be specified together.");
        if (Hflag)
            fts_options |= FTS_COMFOLLOW;
        if (Lflag) {
            fts_options &= ~FTS_PHYSICAL;
            fts_options |= FTS_LOGICAL;
        }
    } else
        fts_options = hflag ? FTS_PHYSICAL : FTS_LOGICAL;

    if (hflag)
        change_mode = lchmod;
    else
        change_mode = chmod;
#ifdef __APPLE__
    if (acloptflags & ACL_FROM_STDIN) {
        int readval = 0, readtotal = 0; 
        mode = (char *) malloc(MAX_ACL_TEXT_SIZE);
        if (mode == NULL)
            err(1, "Unable to allocate mode string");
        /* Read the ACEs from STDIN */
        do {
            readtotal += readval;
            readval = read(STDIN_FILENO, mode + readtotal, 
                       MAX_ACL_TEXT_SIZE);
        } while ((readval > 0) && (readtotal <= MAX_ACL_TEXT_SIZE));

        if (0 == readtotal)
            errx(1, "-E specified, but read from STDIN failed");
        else
            mode[readtotal - 1] = '\0';
        --argv;
    }
    else
#endif /* __APPLE */
        mode = *argv;
#ifdef __APPLE__
    if ((acloptflags & ACL_FLAG)) {
        /* Are we deleting by entry number, verifying
         * canonicity or performing some other operation that
         * does not require an input entry? If so, there's no
         * entry to convert.
         */
        if (ace_arg_not_required) {
            --argv;
        }
        else {
                        /* Parse the text into an ACL*/
            acl_input = parse_acl_entries(mode);
            if (acl_input == NULL) {
                errx(1, "Invalid ACL specification: %s", mode);
            }
        }
    }
    else {
#endif
        if (*mode >= '0' && *mode <= '7') {
            errno = 0;
            val = strtol(mode, &ep, 8);
            if (val > USHRT_MAX || val < 0)
                errno = ERANGE;
            if (errno)
                err(1, "Invalid file mode: %s", mode);
            if (*ep)
                errx(1, "Invalid file mode: %s", mode);
            omode = (mode_t)val;
            oct = 1;
        } else {
            if ((set = setmode(mode)) == NULL)
                errx(1, "Invalid file mode: %s", mode);
            oct = 0;
        }
#ifdef __APPLE__
    }
#endif
    if ((ftsp = fts_open(++argv, fts_options, 0)) == NULL)
        err(1, "fts_open");
    for (rval = 0; (p = fts_read(ftsp)) != NULL;) {
        switch (p->fts_info) {
        case FTS_D:
            if (!Rflag)
                (void)fts_set(ftsp, p, FTS_SKIP);
            break;
        case FTS_DNR:           /* Warn, chmod, continue. */
            warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
            rval = 1;
            break;
        case FTS_DP:            /* Already changed at FTS_D. */
            continue;
        case FTS_NS:
            if (acloptflags & ACL_FLAG) /* don't need stat for -N */
                break;
        case FTS_ERR:           /* Warn, continue. */
            warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
            rval = 1;
            continue;
        case FTS_SL:            /* Ignore. */
        case FTS_SLNONE:
            /*
             * The only symlinks that end up here are ones that
             * don't point to anything and ones that we found
             * doing a physical walk.
             */
            if (!hflag)
                continue;
            /* else */
            /* FALLTHROUGH */
        default:
            break;
        }
#ifdef __APPLE__
/* If an ACL manipulation option was specified, manipulate */
        if (acloptflags & ACL_FLAG) {
            if (0 != modify_file_acl(acloptflags, p->fts_accpath, acl_input, aclpos, inheritance_level))
                rval = 1;
        }
        else {
#endif
            newmode = oct ? omode : getmode(set, p->fts_statp->st_mode);
            if ((newmode & ALLPERMS) == (p->fts_statp->st_mode & ALLPERMS))
                continue;
            if ((*change_mode)(p->fts_accpath, newmode) && !fflag) {
                warn("Unable to change file mode on %s", p->fts_path);
                rval = 1;
            } else {
                if (vflag) {
                    (void)printf("%s", p->fts_accpath);

                    if (vflag > 1) {
                        char m1[12], m2[12];

                        strmode(p->fts_statp->st_mode, m1);
                        strmode((p->fts_statp->st_mode &
                             S_IFMT) | newmode, m2);

                        (void)printf(": 0%o [%s] -> 0%o [%s]",
                                 p->fts_statp->st_mode, m1,
                        (p->fts_statp->st_mode & S_IFMT) |
                                 newmode, m2);
                    }
                    (void)printf("\n");
                }

            }
#ifdef __APPLE__
        }
#endif
    }
    if (errno)
        err(1, "fts_read");
#ifdef __APPLE__
    if (acl_input)
        acl_free(acl_input);
    if (mode && (acloptflags & ACL_FROM_STDIN))
        free(mode);

#endif
    if (set)
        free(set);
    exit(rval);
}
void
usage(void)
{
#ifdef __APPLE__
    (void)fprintf(stderr,
              "usage:\tchmod [-fhv] [-R [-H | -L | -P]] [-a | +a | =a  [i][# [ n]]] mode|entry file ...\n"
              "\tchmod [-fhv] [-R [-H | -L | -P]] [-E | -C | -N | -i | -I] file ...\n"); /* add -A and -V when implemented */
#else
    (void)fprintf(stderr,
        "usage: chmod [-fhv] [-R [-H | -L | -P]] mode file ...\n");
#endif
    exit(1);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.