example.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <stdio.h>
  2. #include "cargs.h"
  3. int main(int argc, char* argv[])
  4. {
  5. __cargs_decimal dbl = 0;
  6. __cargs_int i = 0;
  7. char* str = NULL;
  8. __cargs_bool b1 = __cargs_false;
  9. __cargs_bool b2 = __cargs_false;
  10. __cargs_bool needPrintHelp = __cargs_false;
  11. OptionData options[] = {
  12. decimalArg('d', "decimal", &dbl, "This is a decimal arg.\nHello world"),
  13. integerArg('i', "integer", &i, "This is an integer arg"),
  14. stringArg('s', "string", &str, "This is a string arg"),
  15. booleanArg('b', "boolean", &b1, "This is a first boolean arg"),
  16. booleanArg('k', NULL, &b2, "This is a second boolean arg"),
  17. integerArg(0, "integer-noref", NULL, "Integer arg without ref"),
  18. booleanArg(0, "help", &needPrintHelp, "Open help text"),
  19. integerArg('x', "index", NULL, "Index"),
  20. };
  21. ParseContext context = {
  22. .items = options,
  23. .itemsCount = 8,
  24. };
  25. ParseResult* result = parseArgs(&context, argc, argv);
  26. int errorsStatus = printErrors(&context, result, argc, argv);
  27. if (errorsStatus) {
  28. return 1;
  29. }
  30. if (needPrintHelp) {
  31. printHelp(&context);
  32. return 0;
  33. }
  34. printf("Decimal: %f\n", dbl);
  35. printf("Integer: %d\n", i);
  36. printf("String: %s\n", str);
  37. printf("Boolean 1: %d\n", b1);
  38. printf("Boolean 2: %d\n", b2);
  39. printf("Free values:\n");
  40. for (int i = 0; i < result->freeValuesCount; i++) {
  41. printf(" %s\n", result->freeValues[i]);
  42. }
  43. printf("Integer options (amount: %zu):\n", result->integerOptionsCount);
  44. for (size_t i = 0; i < result->integerOptionsCount; i++) {
  45. const char shortName = options[result->integerOptions[i]].shortOption;
  46. printf(" %c: %d\n", shortName == 0 ? '?' : shortName, result->integerValues[i]);
  47. }
  48. freeResult(result);
  49. return 0;
  50. }