Question

Write a program in C using Unix system calls and functions that will change the permissions on a ...

Write a program in C using Unix system calls and functions that will change the permissions on a file. The executable shall be called “mychmod” and will be executed by:

mychmod -u rwx -g rwx -o rwx -U rwx -G rwx -O rwx file1 file2 ...

The lowercase options will add permissions while the uppercase options will remove permissions. Each of the switches is optional and should be interpreted as the ones in the Unix command chmod(1), you can review the manual (man chmod) pages for more information. Furthermore, the permissions can be specified as any permutation of the string rwx, and can be split over multiple switches such as:

mychmod -u r -u wx -g rx -G w -O wrx file1 file2 ...

If the command cannot be properly parsed, or if there is no file specified, you should print a help message to show usage of the command and exit with a status value of 1. Send the help message to “stderr”. More information in the manual (man stderr) Before you access a file, make sure that the file exists and that you have permissions to access and change the file permissions. Remember, you cannot change permissions if you are not the user owner of the file. In such a case, you should continue with other specified files but return an exit status of 2 at the end of command. Check out the man page for “stat” or “fstat” to get information about the specified file.

A successful execution of command is indicated by a return status of 0.

Here is what I have so far.... I can't remove the file permission, and If I did, I removed all permission instead the one I speficied...

#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>

void DisplayUsage(char *);

/*************************
* main() *
*************************/
int main(int argc, char **argv) {

int c, i;
int fileCount = 0;
//to verify the ownership of a file
// check: "man getuid"

struct stat fileStat;
mode_t addPermissions = 0;
mode_t removePermissions = 0;

c = getopt (argc, argv, "u:g:o:U:G:O:");
//check: "man getopt"
if (c == 'u') {
for (i=0; i < strlen(optarg); i++) {
if (optarg[i] == 'r') { //check: "man optarg"
addPermissions |= S_IRUSR; //man fstat
} else if (optarg[i] == 'w') {
addPermissions |= S_IWUSR;
} else if (optarg[i] == 'x') {
addPermissions |= S_IXUSR;
}
}
}
if (c == 'g') {
for (i=0; i < strlen(optarg); i++) {
if (optarg[i] == 'r') { //check: "man optarg"
addPermissions |= S_IRGRP; //man fstat
} else if (optarg[i] == 'w') {
addPermissions |= S_IWGRP;
} else if (optarg[i] == 'x') {
addPermissions |= S_IXGRP;
}
}
}
if (c == 'o') {
for (i=0; i < strlen(optarg); i++) {
if (optarg[i] == 'r') { //check: "man optarg"
addPermissions |= S_IROTH; //man fstat
} else if (optarg[i] == 'w') {
addPermissions |= S_IWOTH;
} else if (optarg[i] == 'x') {
addPermissions |= S_IXOTH;
}
}
}
if (c == 'U') {
for (i = 0; i < strlen(optarg); i++) {
if (optarg[i] == 'r') { //check: "man optarg"
removePermissions &= ~(S_IRUSR);
} else if (optarg[i] == 'w') {
removePermissions &= ~(S_IWUSR);
} else if (optarg[i] == 'x') {
removePermissions &= ~(S_IXUSR);
}
}
}
if (c == 'G') {
for (i = 0; i < strlen(optarg); i++) {
if (optarg[i] == 'r') { //check: "man optarg"
removePermissions &= ~(S_IRGRP);
} else if (optarg[i] == 'w') {
removePermissions &= ~(S_IWGRP);
} else if (optarg[i] == 'x') {
removePermissions &= ~(S_IXGRP);
}
}
}
if (c == 'O') {
for (i = 0; i < strlen(optarg); i++) {
if (optarg[i] == 'r') { //check: "man optarg"
removePermissions &= ~(S_IROTH);
} else if (optarg[i] == 'w') {
removePermissions &= ~(S_IWOTH);
} else if (optarg[i] == 'x') {
removePermissions &= ~(S_IXOTH);
}
}
}

// Change permissions
// here we can use optind
stat(argv[3], &fileStat);
fileStat.st_mode &= removePermissions;
fileStat.st_mode |= addPermissions;
chmod(argv[3], fileStat.st_mode);

//check: "man optind"

return 0;
}

/************************
* DisplayUsage() *
************************/
void DisplayUsage(char *programName) {
printf("Usage:\n ./Vo_Vananh_CMPS3600_Lab11 -u rwx -g rwx -o rwx -U rwx -G rwx -O rwx file1 file2 ...\n");
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Solution:-

  • I have implemented the above question as per the requirement given in the question.
  • i have attached the screenshot of the running without argument and runningwith with invalid option.

Source code-

#include <stdlib.h> 
#include <stdio.h>    
#include <ctype.h>    
#include <unistd.h>   
#include <sys/stat.h>
#include <string.h>

void DisplayUsage(char *);

/*****************************************************************************
 *    main()                                                                 *
 *****************************************************************************/

int main(int argc, char **argv) {

  int c;
  int i;
  int index;
  int fileCount = 0;

  char isFileError = 0;
  uid_t myUid = getuid();

  struct stat fileStat;
  mode_t addPermissions = 0;
  mode_t removePermissions = 0;

  opterr = 0; // prevents the default error messages of getopt() 

  while ((c = getopt (argc, argv, "u:g:o:U:G:O:")) != -1) { // Parse cli args
    switch (c) {
 
    case 'u':
      for (i=0; i<strlen(optarg); i++) {
        if (optarg[i] == 'r') 
          addPermissions |= S_IRUSR;
        else if (optarg[i] == 'w') 
          addPermissions |= S_IWUSR;
        else if (optarg[i] == 'x') 
          addPermissions |= S_IXUSR;
      }
      break;

    case 'g':
      for (i=0; i<strlen(optarg); i++) {
        if (optarg[i] == 'r') 
          addPermissions |= S_IRGRP;
        else if (optarg[i] == 'w') 
          addPermissions |= S_IWGRP;
        else if (optarg[i] == 'x') 
          addPermissions |= S_IXGRP;
      }
      break;

    case 'o':
      for (i=0; i<strlen(optarg); i++) {
        if (optarg[i] == 'r') 
          addPermissions |= S_IROTH;
        else if (optarg[i] == 'w') 
          addPermissions |= S_IWOTH;
        else if (optarg[i] == 'x') 
          addPermissions |= S_IXOTH;
      }
      break;

    case 'U':
      for (i=0; i<strlen(optarg); i++) {
        if (optarg[i] == 'r') 
          removePermissions |= S_IRUSR;
        else if (optarg[i] == 'w') 
          removePermissions |= S_IWUSR;
        else if (optarg[i] == 'x') 
          removePermissions |= S_IXUSR;
      }
      break;

    case 'G':
      for (i=0; i<strlen(optarg); i++) {
        if (optarg[i] == 'r') 
          removePermissions |= S_IRGRP;
        else if (optarg[i] == 'w') 
          removePermissions |= S_IWGRP;
        else if (optarg[i] == 'x') 
          removePermissions |= S_IXGRP;
      }
      break;

    case 'O':
      for (i=0; i<strlen(optarg); i++) {
        if (optarg[i] == 'r') 
          removePermissions |= S_IROTH;
        else if (optarg[i] == 'w') 
          removePermissions |= S_IWOTH;
        else if (optarg[i] == 'x') 
          removePermissions |= S_IXOTH;
      }
      break;

    case '?': // getopt detected invalid option character or missing target

      if (optopt == 'u' || optopt == 'g' || optopt == 'o' ||\
          optopt == 'U' || optopt == 'G' || optopt == 'O')
        fprintf (stderr, "\n\t***Option -%c requires an argument***\n", optopt);
      else if (isprint (optopt))
        fprintf (stderr, "\n\t***Unknown option `-%c'***\n", optopt);
      else
        fprintf (stderr, "\n\t***Unknown option character `\\x%x'***\n", optopt);

      DisplayUsage(argv[0]);

      printf("Exit status: 1\n");
      return 1; // Error!

    default:
      abort (); // Critical Error!
    }
  }

  if (argc == 1)
    DisplayUsage(argv[0]);

  else { // Change permission for each file

    for (index = optind; index < argc; index++) { 
      ++fileCount;
  
      if ( stat(argv[index], &fileStat) < 0) { // Check if file exists
        perror("Stat()");
        isFileError = 1; 
      }
  
      // Check if user owns file or if root
      else if (fileStat.st_uid != myUid && myUid != 0) { 
        fprintf(stderr, "UID ERROR: You do not own this file\n");
        isFileError = 1;
      }
      
      fileStat.st_mode |= addPermissions;
      fileStat.st_mode &= ~removePermissions;

      if ( chmod(argv[index], fileStat.st_mode) == -1) {
        perror(argv[index]);
        isFileError = 1;
      }
    }  
  }
  
  if (fileCount == 0) {
    printf("No file specified\nExit Status: 2\n");
    return 2;
  }

  if (isFileError) {
    printf("Exit status: 2\n");
    return 2;
  }
  else {
    printf("Exit status: 0\n");
    return 0;
  }
}

/*****************************************************************************
 *    DisplayUsage()                                                         *
 *****************************************************************************/

void DisplayUsage(char *programName) {
  fprintf(stderr, "\nSYNOPSIS\n    %s OPTION... PERMISSION... FILE...\n",\
          programName);
      
  fprintf(stderr, "\nDESCRIPTION\n    Uses unix system calls and functions");
  fprintf(stderr, " to change\n    the permissions on one or more files.\n");

  fprintf(stderr, "\nOPTIONS\n    \t-u\n\t    Add permissions for user.");
  fprintf(stderr, "\n\t-g\n\t    Add permissions for group.");
  fprintf(stderr, "\n\t-o\n\t    Add permissions for other.");
  fprintf(stderr, "\n\t-U\n\t    Remove permissions for user.");
  fprintf(stderr, "\n\t-G\n\t    Remove permissions for group.");
  fprintf(stderr, "\n\t-O\n\t    Remove permissions for group.\n");

  fprintf(stderr, "\nPERMISSIONS\n    \tr\n\t    READ");
  fprintf(stderr, "\n\tw\n\t    WRITE");
  fprintf(stderr, "\n\tx\n\t    EXECUTE\n");
}

----------------------------------------------------------------------------------------------------------------------------

Makefile:-

CC=gcc
CFLAGS=-c -Wall -g

SOURCES=$(wildcard src/*.c)
OBJECTS=$(notdir $(SOURCES:.c=.o))

EXECUTABLE=mychmod

all: $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)  
        $(CC) $(OBJECTS) -o $(EXECUTABLE) 

%.o: src/%.c
        $(CC) $(CFLAGS) $< -o $@

.PHONY: clean

clean:
        rm $(OBJECTS) $(EXECUTABLE)

--------------------------------------------------------------------------------------------------

Output:-

initial compilation and running without arguments

sentient@Wilderness:-/dev/C/Project-2$ pwd home/sentient/dev/C/Project-2 sentient@Wilderness: /dev/C/Project-2$ ls Makefile M

Running with invalid option

sentient@Wilderness:~/dev/C/Project-2$ ./mychmod f ***Unknown option f ** SYNOPSIS ./nychnod OPTION.. PERMISSION... FILE... D

-------------------------------------------------------------------------------------------------------------

if you are satisfy with my answer then please,please like my answer.

Add a comment
Know the answer?
Add Answer to:
Write a program in C using Unix system calls and functions that will change the permissions on a ...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Objective: Practice common UNIX commands. Procedure: The following list of Unix commands are given for self-learning....

    Objective: Practice common UNIX commands. Procedure: The following list of Unix commands are given for self-learning. Use 'whatis' or 'man' command to find out about each command. Your document should include the description or screen shots of the output from each of the command. Commands: df du gzip file history wget Changing access rights: chmod u+x Dir1.0            adds execute permission for the owner chmod go-w file1              removes write permission for the group and others chmod ugo=rw testfile     sets...

  • Convert C to C++ I need these 4 C file code convert to C++. Please Convert...

    Convert C to C++ I need these 4 C file code convert to C++. Please Convert it to C++ //////first C file: Wunzip.c #include int main(int argc, char* argv[]) { if(argc ==1){ printf("wunzip: file1 [file2 ...]\n"); return 1; } else{ for(int i =1; i< argc;i++){ int num=-1; int numout=-1; int c; int c1;    FILE* file = fopen(argv[i],"rb"); if(file == NULL){ printf("Cannot Open File\n"); return 1; } else{ while(numout != 0){    numout = fread(&num, sizeof(int), 1, file);    c...

  • Hi, need this question ansered in c++, has multiple levels will post again if you can...

    Hi, need this question ansered in c++, has multiple levels will post again if you can complete every level so keep an eye out for that. here is a sketch of the program from the screenshot int main (int argc, char** argv) { enum { total, unique } mode = total; for (int c; (c = getopt(argc, argv, "tu")) != -1;) { switch(c) { case 't': mode = total; break; case 'u': mode = unique; break; } } argc -=...

  • I have the following code....from the previous lab....the above needs to be added to what is...

    I have the following code....from the previous lab....the above needs to be added to what is already existing. ALSO MODIFY SEMAPHORES TO USE pthreads instead of the pipe constructs P() & V() #include <stdio.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <stdlib.h> #include <sys/stat.h> void printStat(char *filename); //Main int main(int argc, char *argv[]) { //Process Id (storing)    pid_t pid;    int j;    //printf("Welcome to Project Three\n”);    // For loop*/    for (j = 1; j...

  • Purpose This assignment should give you experience in using file descriptors, open(), close(), wr...

    Purpose This assignment should give you experience in using file descriptors, open(), close(), write(), stat() and chmod(), perror(), and command line arguments. Program Write a C++ program that will allow you to add messages to a file that has NO permissions for any user. A Unix system has many files that have sensitive information in them. Permissions help keep these files secure. Some files can be publicly read, but can not be altered by a regular user (ex.: /etc/passwd). Other...

  • Write a complete C program that inputs a paragraph of text and prints out each unique...

    Write a complete C program that inputs a paragraph of text and prints out each unique letter found in the text along with the number of times it occurred. A sample run of the program is given below. You should input your text from a data file specified on the command line. Your output should be formatted and presented exactly like the sample run (i.e. alphabetized with the exact spacings and output labels). The name of your data file along...

  • Write a C++ program In this assignment you will complete the definition of two functions that...

    Write a C++ program In this assignment you will complete the definition of two functions that implement the repeated squaring algorithm described in the Stamp textbook on pages 98-99. Note that your implementation should not use the pow() function, the powl() functions, or any other built-in exponentiation functions. program4-driver.cpp - This file contains a completed main() function that serves as the driver to parse the command line, pass the values to the powerModN() function, and print the result. Make no...

  • operating system programming i need ans and explen after 20 min 2 When we are implementing...

    operating system programming i need ans and explen after 20 min 2 When we are implementing the following program, then we press "CTRL+C" on the keyboard; that will cause: #include <stdio.h> #include<signal.h> #include <stdlib.h> #include<unistd.h> void handle_sigint (int sig) { } printf("Caught signal $d\n", sig); int main(int argc, char *argv[]) { signal (SIGCONT, handle_sigint); while (1) { printf("the process id is $d \n",getpid()); sleep (1); } return 0; } O print the sentence" Caught signal 2" on the terminal 53,65,67,37,14,98,122,124,183...

  • C Language Programming. Using the program below - When executing on the command line only this...

    C Language Programming. Using the program below - When executing on the command line only this program name, the program will accept keyboard input and display such until the user does control+break to exit the program. The new code should within only this case situation “if (argc == 1){ /* no args; copy standard input */” Replace line #20 “filecopy(stdin, stdout);” with new code. Open read a text file “7NoInputFileResponse.txt” that contains a message “There were no arguments on the...

  • I need to rewrite this program using only RIO I/O functions on c 6 Write a...

    I need to rewrite this program using only RIO I/O functions on c 6 Write a C program that asks the user to enter the fil he all its permissions in a readable format.) Also, the program prints the file contents to the standard output if the file is of a regular type. Use only Unix V/O functions. Do not use the O package nor C standard I/O functions. Save your source file as "lab07a.c" and include it in the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT