GetGecos

lies die GecosInfos aus der /etc/passwd aus.

getgecos.c
#include <pwd.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
//---------------------------------------
void string_split(char * string, char sep, char *** r_array_string, int * r_size) {
    int i, k, len, size;
    char ** array_string;
 
    // Number of substrings
    size = 1, len = strlen(string);
    for(i = 0; i < len; i++) {
	if(string[i] == sep) {
	    size++;
	}
    }
 
    array_string = malloc(size * sizeof(char*));
 
    i=0, k=0;
    array_string[k++] = string; // Save the first substring pointer
    // Split 'string' into substrings with \0 character
    while(k < size) {
	if(string[i++] == sep) {
	    string[i-1] = '\0'; // Set end of substring
	    array_string[k++] = (string+i); // Save the next substring pointer
	}
    }
    *r_array_string = array_string;
    *r_size = size;
    return;
}
//-------------------------------------------
int getgecos(char* user)
{
    struct passwd pwd;
    struct passwd *result;
    char *buf;
    size_t bufsize;
    int s;
    char *p;
 
    bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
    if (bufsize == -1)          /* Value was indeterminate */
        bufsize = 16384;        /* Should be more than enough */
 
        buf = malloc(bufsize);
        if (buf == NULL) {
            perror("malloc");
            exit(EXIT_FAILURE);
           }
         s = getpwnam_r(user, &pwd, buf, bufsize, &result);
         if (result == NULL) {
             if (s == 0)
                 printf("user not found\n");
             else {
                   errno = s;
                   perror("getpwnam_r");
               }
               exit(EXIT_FAILURE);
           }
           printf("%s\n", pwd.pw_gecos);
 
    char ** array_string;
    int i, size;
 
    string_split(pwd.pw_gecos, ',', &array_string, &size);
    printf("Number of substrings: %d \n", size);
    for(i = 0; i < size; i++) {
	printf("%d: %s \n", i, array_string[i]);
    }
 
    free(array_string);
 
   return(EXIT_SUCCESS);
}
//---------------------------------------------
int main(int argc, char *argv[])
  {
    int i;
    if (argc != 2) {
        fprintf(stderr, "Usage: %s username\n", argv[0]);
        exit(EXIT_FAILURE);
        }
	i = getgecos(argv[1]);
	return i;
   }