add getopt functionality

This commit is contained in:
Chris Cromer 2018-11-11 13:27:38 -03:00
parent 440993b596
commit e4554314ed
Signed by: cromer
GPG Key ID: 39CC813FF3C8708A
1 changed files with 122 additions and 2 deletions

View File

@ -14,6 +14,11 @@
*/
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include "random.h"
#define SORT_VERSION "1.0.0"
/**
* Imprimir el uso del programa
@ -34,12 +39,127 @@ void print_usage() {
fprintf(stdout, " -v, --version mostrar la versión del programa\n");
}
/**
* Imprimir un mensaje de error y salir
*/
void extra_algorithm() {
fprintf(stderr, "Error: Solo se puede elegir un algoritmo al vez!\n");
print_usage();
exit(2);
}
/**
* La entrada del programa
* @param argc La cantidad de argumentos pasado al programa
* @return Returna el codigo de error o 0 por exito
* @return Retorna el codigo de error o 0 por exito
*/
int main (int argc, char **argv) {
print_usage();
int i;
int n = 10;
int elegir = 0;
int algoritmo = -1;
int opt;
int long_index = 0;
static struct option long_options[] = {
{"merge", no_argument, 0, 'm'},
{"quick", no_argument, 0, 'q'},
{"bubble", no_argument, 0, 'b'},
{"bitonic", no_argument, 0, 'B'},
{"count", no_argument, 0, 'c'},
{"selection", no_argument, 0, 's'},
{"n", required_argument, 0, 'n'},
{"elegir", no_argument, 0, 'e'},
{"version", no_argument, 0, 'v'},
{0, 0, 0, 0}
};
if (argc == 1) {
print_usage();
return 0;
}
while ((opt = getopt_long(argc, argv, "mqbBcsn:ev", long_options, &long_index)) != -1) {
switch (opt) {
case 'm':
if (algoritmo != -1) {
extra_algorithm();
}
algoritmo = 0;
break;
case 'q':
if (algoritmo != -1) {
extra_algorithm();
}
algoritmo = 1;
break;
case 'b':
if (algoritmo != -1) {
extra_algorithm();
}
algoritmo = 2;
break;
case 'B':
if (algoritmo != -1) {
extra_algorithm();
}
algoritmo = 3;
break;
case 'c':
if (algoritmo != -1) {
extra_algorithm();
}
algoritmo = 4;
break;
case 's':
if (algoritmo != -1) {
extra_algorithm();
}
algoritmo = 5;
break;
case 'n':
n = atoi(optarg);
if (n <= 1) {
fprintf(stderr, "Error: n tiene que ser mayor de 1!\n");
return 3;
}
break;
case 'e':
elegir = 1;
break;
case 'v':
printf("sort versión: %s\n", SORT_VERSION);
return 0;
break;
default:
print_usage();
return 1;
}
}
if (algoritmo == -1) {
fprintf(stderr, "Error: No se seleccionó un algoritmo!\n");
print_usage();
return 4;
}
int array[n];
// Llenar el array con valores para ordenar después
for (i = 0; i < n; i++) {
if (elegir == 0) {
array[i] = gen_rand(0, 100000);
}
else {
opt = 0;
while (opt <= 1) {
fprintf(stdout, "Elegir elemento %d: ", i + 1);
fscanf(stdin, "%d", &opt);
if (opt <= 1) {
fprintf(stdout, "Número invalido! Tiene que ser mayor de 1!\n");
}
}
array[i] = opt;
}
}
return 0;
}