Answer to Question #118151 in C for bhagyashree

Question #118151
write a program in c to mimic the “deluser” command on linux. this command will delete system 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 (refer man pages for the command line arguments).
1
Expert's answer
2020-05-28T10:39:13-0400
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    char line_1[100], line_2[100];
    char data_1[100][100], data_2[100][100];
    FILE *PFILE;
    int length, i = 0, j = 0, counter = 0;
    int k = 0, l = 0;

    if ((PFILE = fopen("shadow", "r")) != NULL) {
        while (fgets(line_1, sizeof(line_1), PFILE)) {
            length = strlen(line_1);
            if (length > 0 && line_1[length - 1] == '\n')
                line_1[--length] = '\0';
            if (strcmp(line_1, argv[1]) == 0) {
                counter = i;
                ++i;
                continue;
            }

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


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


        if ((PFILE = fopen("passwd", "r")) != NULL) {
            while (fgets(line_2, sizeof(line_2), PFILE)) {
                length = strlen(line_2);
                if (length > 0 && line_2[length - 1] == '\n')
                    line_2[--length] = '\0';
                if (counter == k) {
                    ++k;
                    continue;
                }


                strcat(line_2, "\n");
                strcpy(data_2[k], line_2);
                printf("%s", data_2[k]);
                ++k;

            }
            fclose(PFILE);


            PFILE = fopen("passwd", "w");
            while (l < k) {
                fputs(data_2[l], PFILE);
                ++l;

            }
            fclose(PFILE);
            printf("User %s was deleted.\n", argv[1]);


            return 0;
        } else {
            printf("File open error!");
            exit(1);

        }
    } else {
        printf("File open error!");

        exit(1);
    }
}

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

bhagyashree
28.05.20, 21:01

Hello expert, after executing the code it is showing "segmentation fault (core dump)".

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS