Skip to content

Instantly share code, notes, and snippets.

@artur-kink
Created September 9, 2014 17:46
Show Gist options
  • Save artur-kink/e23999a92bc92328dc61 to your computer and use it in GitHub Desktop.
Save artur-kink/e23999a92bc92328dc61 to your computer and use it in GitHub Desktop.
Shell program to display age of person given their date of birth.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
void printhelp(){
printf("Get age of person.\n\n");
printf("Usage: age -d <day> -m <month> -y <year>\n");
printf("Arguments\n");
printf(" -h\tprint this.\n");
printf(" -d\tday of birth. \n");
printf(" -m\tmonth of birth.\n");
printf(" -y\tyear of birth.\n");
}
int main(int argc, char** argv){
int c;
int d = -1;
int m = -1;
int y = -1;
//Get age params
while ((c = getopt(argc, argv, ":d:m:y:")) != -1) {
switch(c) {
case 'd':
d = atoi(optarg);
break;
case 'm':
m = atoi(optarg);
break;
case 'y':
y = atoi(optarg);
break;
default:
printhelp();
return 1;
}
}
//Make sure all parameters were given.
if(d == -1 || m == -1 || y == -1){
printhelp();
return -1;
}
//Initialize time variables.
time_t now = time(0);
struct tm* now_tm = localtime(&now);
struct tm dob;
dob.tm_sec = 0;
dob.tm_min = 0;
dob.tm_hour = 0;
dob.tm_year = y-1900;
dob.tm_mon = m-1;
dob.tm_mday = d-1;
//Get age and display it.
double age = difftime(now, mktime(&dob));
printf("%f\n", age/60/60/24/365.242199);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment