Argument parsing!

This commit is contained in:
Nicolás A. Ortega 2016-12-14 17:52:52 +01:00
parent b5dcadce19
commit c522196d66
No known key found for this signature in database
GPG Key ID: 614272579C2070D1

View File

@ -2,21 +2,58 @@
#include <stdlib.h> #include <stdlib.h>
#include <signal.h> #include <signal.h>
#include <stdbool.h> #include <stdbool.h>
#include <getopt.h>
#include <gmp.h> #include <gmp.h>
#include "list.h" #include "list.h"
#define VERSION "v0.5"
static bool run; static bool run;
void printUsage(char *progName);
void leave(); void leave();
int main(void) { int main(int argc, char *argv[]) {
puts("Indivisible v0.5\n"); bool f_help = false, f_version = false, f_quiet = false;
int c;
while((c = getopt(argc, argv, "hvq")) != -1) {
switch(c) {
case 'h':
f_help = true;
break;
case 'v':
f_version = true;
break;
case 'q':
f_quiet = true;
break;
default:
printUsage(argv[0]);
exit(1);
}
}
if(f_help) {
printUsage(argv[0]);
puts(" -h print this help information");
puts(" -v print version number of program");
puts(" -q quiet mode");
return 0;
} else if(f_version) {
printf("Indivisible %s\n", VERSION);
return 0;
}
// Quit on ^C by setting `run = false' // Quit on ^C by setting `run = false'
run = true; run = true;
signal(SIGINT, leave); signal(SIGINT, leave);
if(f_quiet) {
puts("Use Ctrl+C (SIGINT) to exit.");
}
// Primes we've found // Primes we've found
List primes; List primes;
initList(&primes); initList(&primes);
@ -28,11 +65,13 @@ int main(void) {
// Add 2, a known prime to this list // Add 2, a known prime to this list
mpz_set_ui(num, 2); mpz_set_ui(num, 2);
addToList(&primes, num); addToList(&primes, num);
if(mpz_out_str(stdout, 10, num) == 0) { if(!f_quiet) {
fprintf(stderr, "Could not print to `stdout'!\n"); if(mpz_out_str(stdout, 10, num) == 0) {
exit(1); fprintf(stderr, "Could not print to `stdout'!\n");
exit(1);
}
printf("\n");
} }
printf("\n");
mpz_add_ui(num, num, 1); mpz_add_ui(num, num, 1);
// Variable for half `num' // Variable for half `num'
@ -54,11 +93,13 @@ int main(void) {
// `num' is a prime so we add it to the list and print it // `num' is a prime so we add it to the list and print it
addToList(&primes, num); addToList(&primes, num);
if(mpz_out_str(stdout, 10, num) == 0) { if(!f_quiet) {
fprintf(stderr, "Could not print to `stdout'!\n"); if(mpz_out_str(stdout, 10, num) == 0) {
exit(1); fprintf(stderr, "Could not print to `stdout'!\n");
exit(1);
}
printf("\n");
} }
printf("\n");
nextPrime: nextPrime:
// Add 2 (skip even numbers since they're all divisible by 2) // Add 2 (skip even numbers since they're all divisible by 2)
@ -77,4 +118,8 @@ nextPrime:
return 0; return 0;
} }
void printUsage(char *progName) {
printf("%s [-v | -h | -q]\n", progName);
}
void leave() { run = false; } void leave() { run = false; }