Answer to Question #116567 in C for lex

Question #116567
Write a program in C to mimic the “deluser” command on Linux. This command will delete a user. 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
1
Expert's answer
2020-05-18T17:03:30-0400
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // For exit() function
int main(int argc, char *argv[]) {
    char line[100], line2[100];
    char data1[100][100], data2[100][100];
    FILE *PFILE;
    int len, i=0, j=0, counter = 0;
    int k=0,l=0;


    //update username file
    if ((PFILE = fopen("shadow", "r")) == NULL) {
        printf("Error! opening file");
        // Program exits if file pointer returns NULL.
        exit(1);
    }


   while (fgets(line, sizeof(line), PFILE)) {
        len = strlen(line);
        if(len > 0 && line[len-1] == '\n')
            line[--len] = '\0';
        if(strcmp(line, argv[1]) == 0){
            counter = i;
            ++i;
            continue;
        }


        strcat(line,"\n");
        strcpy(data1[i],line);
        ++i;
    }
    fclose(PFILE);


    PFILE = fopen("shadow", "w");
    while(j < i){
        fputs(data1[j],PFILE);
        ++j;
    }
    fclose(PFILE);


/////////////////////////////////////////////////////////////////////////////////////////    
    //update password file
    if ((PFILE = fopen("passwd", "r")) == NULL) {
        printf("Error! opening file");
        // Program exits if file pointer returns NULL.
        exit(1);
    }
    while (fgets(line2, sizeof(line2), PFILE)) {
        len = strlen(line2);
        if(len > 0 && line2[len-1] == '\n')
            line2[--len] = '\0';
        if(counter == k){
            ++k;
            continue;
        }


        strcat(line2,"\n");
        strcpy(data2[k],line2);
        printf("%s",data2[k]);
        ++k;
    }
    fclose(PFILE);


    PFILE = fopen("passwd", "w");
    while(l < k){
        fputs(data2[l],PFILE);
        ++l;
    }
    fclose(PFILE);
    printf("User %s is deleted from File.\n", argv[1]);


    return 0;
}



shadow file

user1

user2

user3

user4

user5

user6

user7

user8


passwd file


1111

2222

3333

4444

5555

6666

7777

8888




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!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS