Must be done in C. Write a program for the following man page: NAME cm – changes
ID: 3719363 • Letter: M
Question
Must be done in C.
Write a program for the following man page:
NAME
cm – changes the permissions (rwx) for a owner of file
SYNOPSIS
cm FILE [rwx]
DESCRIPTION
Changes the owner permissions for a specified file.
EXAMPLES
cm
displays synopsis message
cm file rwx
changes the permissions for the owner of the file to rwx
cm file rw
changes the permissions for the owner of the file to rw
cm file rx
changes the permissions for the owner of the file to rx
cm badfile r
displays an appropriate error message since badfile does not exist
cm file
clears all permissions
NOTES
o Does not use C++ specific code
cm
displays synopsis message
cm file rwx
changes the permissions for the owner of the file to rwx
cm file rw
changes the permissions for the owner of the file to rw
cm file rx
changes the permissions for the owner of the file to rx
cm badfile r
displays an appropriate error message since badfile does not exist
cm file
clears all permissions
Explanation / Answer
#include<stdio.h>
#include<sys/stat.h>
#include<string.h>
int main(int argc,char ** argv)
{
char cmd[128],path[128];
struct stat st;
mode_t mode;
const char* file = argv[1];
sprintf(cmd,"ls -l %s",argv[1]);
int errno=0;
if(argc == 2)
{
stat(file,&st);
mode = st.st_mode & 0000;
//mode & = ~(S_IRUSR);
printf(" Clearing all permissions for file ",argv[1]);
errno=chmod(argv[1],mode);
if(errno < 0)
printf("ERROR");
else
return 0;
}
if(argc != 3)
{
printf("Usage : %s filename ",argv[0]);
return 0;
}
sprintf(path,"pwd %s",argv[1]);
if(strcmp(argv[2],"rwx") == 0)
{
printf(" changing permission of file %s to rwx ",argv[1]);
errno=chmod(argv[1], S_IRWXU);
if(errno < 0)
printf("ERROR");
else
return 0;
}
else if(strcmp(argv[2],"rw") == 0)
{
printf(" changing permission of file %s to rw ",argv[1]);
errno=chmod(argv[1], S_IRUSR|S_IWUSR);
if(errno < 0)
printf("ERROR");
else
return 0;
}
else if(strcmp(argv[2],"rx") == 0)
{
printf(" changing permission of file %s to rx ",argv[1]);
errno=chmod(argv[1], S_IXUSR|S_IRUSR);
if(errno < 0)
printf("ERROR");
else
return 0;
}
else if(strcmp(argv[2],"r") == 0 && strcmp(argv[1],"badfile")==0)
{
printf(" Bad file does not exist");
return 0;
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.