Question #116813

Write a program in C to mimic the “delgroup” command on Linux. This command will delete a group. It has to handle 2 files “passwd” and “shadow”. Both these files will be in some folder specified by an environment variable PFILE. The program has to take all arguments as command line arguments

Expert's answer

#include<stdio.h>
#include<string.h>
void main(int arg,char *args[])
{
 int i,found=0,parg,max,len,got,counter=0;
 char path[1000],ppath[1000],p[1000],line[100],linep[100];
 FILE *FILEP1,*FILEP2,*FILET1,*FILET2;
 for(i=1;i<arg;i++)
 {
 if(args[i][0]=='P' && args[i][1]=='F' && args[i][2]=='I' && args[i][3]=='L' && args[i][4]=='E' && args[i][5]=='=')
  {
    found=1;
    parg=i; 
    break;
  }
 }
 if(found==1)
 {
  if(args[parg][6]=='"')
  {
   i=7;
   max=strlen(args[parg])-1; 
  }
  else
  {
   i=6;
   max=strlen(args[parg]); 
  }  
  for(i;i<max;i++)
  {
   path[i-5]=args[parg][i];
  }
  strcpy(ppath,path); 
  strcat(path,"/shadow.txt");
  strcat(ppath,"/passwd.txt"); 
  for(i=1;i<strlen(path);i++)
 {
  path[i-1]=path[i];
 }
 path[i-1]='\0';
 for(i=1;i<strlen(ppath);i++)
 {
  ppath[i-1]=ppath[i];
 }
 ppath[i-1]='\0';
 }
 else
 {
  strcpy(path,"shadow.txt");
  strcpy(ppath,"passwd.txt"); 
 } 


 FILEP1 = fopen(path, "r");
 FILEP2 = fopen(ppath,"r");
 FILET1 = fopen("temp1.txt", "w");
 FILET2 = fopen("temp2.txt", "w");
 if((FILEP1 == NULL) && (FILEP2 == NULL)) 
 {
 
       printf("Error! file not found");


       exit(1);


 }


 
 while(fgets(line, sizeof(line), FILEP1) && fgets(linep, sizeof(linep),FILEP2))
 {
    
   got=0;
   len = strlen(line);
       
   if(len > 0 && line[len-1] == '\n')


   {
            line[--len] = '\0';


   }
   for(i=1;i<arg;i++)
   {
      if(i!=parg && strcmp(line, args[i]) == 0)
      {


        counter++;
        got = 1; 
           


      }
  
 }
   if(got==0)
   {
    strcat(line,"\n");
    fputs(line,FILET1);


 
    fputs(linep,FILET2); 
    printf(line," Deleted Successfully");
   }
   else
   {
    printf(line," Not found!"); 
   }
  }
 
   fclose(FILEP1);
   fclose(FILEP2);
   fclose(FILET1);
   fclose(FILET2);






  printf("Total %d accounts deleted.",counter);
  remove(path);
  remove(ppath);
  rename("temp1.txt",path);
  rename("temp2.txt",ppath);
}



Shadow file


id1

id2

id3

id4

id5

id6

id7

id8

id9

id10

id11

id12


passwd file


pwd1

pwd2

pwd3

pwd4

pwd5

pwd6

pwd7

pwd8

pwd9

pwd10

pwd11

pwd12


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS