diff --git a/shperm.c b/shperm.c index 043b8df..509fe59 100644 --- a/shperm.c +++ b/shperm.c @@ -25,9 +25,7 @@ int linesNo = 0; int maxUsername = 0; int maxGroupname = 0; -void addLine(char* path, int permissions, int uid, int gid) { - linesNo++; - +void mallocLines() { // add one line to the lines array if (linesNo == 1) { lines = malloc(sizeof(*lines)); @@ -37,27 +35,9 @@ void addLine(char* path, int permissions, int uid, int gid) { exit(4); } } +} - // calculate line (index) we are at, which is 0-based (thus -1) - int idx = linesNo - 1; - - // print user - struct passwd* user = getpwuid(uid); - lines[idx].username = malloc(strlen(user->pw_name) + 1); - strcpy(lines[idx].username, user->pw_name); - if (maxUsername < strlen(lines[idx].username)) { - maxUsername = strlen(lines[idx].username); - } - - // print group - struct group* group = getgrgid(gid); - lines[idx].groupname = malloc(strlen(group->gr_name) + 1); - strcpy(lines[idx].groupname, group->gr_name); - if (maxGroupname < strlen(lines[idx].groupname)) { - maxGroupname = strlen(lines[idx].groupname); - } - - // print permissions +void addPermission2Line(int idx, int permissions) { strcpy(lines[idx].permissionStr[0], "---"); strcpy(lines[idx].permissionStr[1], "---"); strcpy(lines[idx].permissionStr[2], "---"); @@ -88,8 +68,37 @@ void addLine(char* path, int permissions, int uid, int gid) { lines[idx].permissionStr[permissionUGO][permissionRWX] = 'x'; } } +} - // print current path +void addLine(char* path, int permissions, int uid, int gid) { + linesNo++; + + // allocate memory for another line + mallocLines(); + + // calculate line (index) we are at, which is 0-based (thus -1) + int idx = linesNo - 1; + + // add user + struct passwd* user = getpwuid(uid); + lines[idx].username = malloc(strlen(user->pw_name) + 1); + strcpy(lines[idx].username, user->pw_name); + if (maxUsername < strlen(lines[idx].username)) { + maxUsername = strlen(lines[idx].username); + } + + // add group + struct group* group = getgrgid(gid); + lines[idx].groupname = malloc(strlen(group->gr_name) + 1); + strcpy(lines[idx].groupname, group->gr_name); + if (maxGroupname < strlen(lines[idx].groupname)) { + maxGroupname = strlen(lines[idx].groupname); + } + + // calculate and add permission + addPermission2Line(idx, permissions); + + // add current path lines[idx].path = malloc(strlen(path) + 1); strcpy(lines[idx].path, path); }