Last active
January 3, 2018 19:49
-
-
Save filosofisto/a3a69bf8745519fc7e3ac6d699364231 to your computer and use it in GitHub Desktop.
Sample using getopt.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cmake_minimum_required(VERSION 3.9) | |
project(params) | |
set(CMAKE_CXX_STANDARD 98) | |
add_executable(params main.cpp) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstdlib> | |
#include <unistd.h> | |
#include <sstream> | |
using namespace std; | |
int main(int argc, char **argv) { | |
cout << "Parametros" << endl; | |
int procs, opt; | |
stringstream loglevel; | |
if (argc < 2) { | |
cerr << "Show usage here! "<< endl; | |
return EXIT_FAILURE; | |
} | |
// Parameters | |
while ((opt = getopt(argc, argv, ":n:l:")) != -1) { | |
switch (opt) { | |
case 'n': | |
procs = atoi(optarg); | |
break; | |
case 'l': | |
loglevel.str(string()); | |
loglevel << optarg; | |
break; | |
case ':': | |
// Exemplo: -n 10 -l | |
cerr << "Faltando valor para o parametro: " << (char) optopt << endl; | |
return EXIT_FAILURE; | |
case '?': | |
// Exemplo: -n 10 -l info -w | |
cerr << "Parametro desconhecido: " << (char) optopt << endl; | |
return EXIT_FAILURE; | |
default: | |
cerr << "Erro de parametros" << endl; | |
return EXIT_FAILURE; | |
} | |
} | |
if (loglevel.str().size() == 0) { | |
// Exemplo: -n 10 | |
cerr << "LogLevel invalido" << endl; | |
return EXIT_FAILURE; | |
} | |
if (optind < argc) { | |
cerr << "Argumento invalido: " << argv[optind] << endl; | |
return EXIT_FAILURE; | |
} | |
if (optind > argc) { | |
cerr << "Erro de parametros" << endl; | |
return EXIT_FAILURE; | |
} | |
cout << "Processos: " << procs << endl; | |
cout << "LogLevel: " << loglevel.str() << endl; | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment