parsechar.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. Test to see if we can parse characters such as "+" or "%" off of a given
  3. command-line argument.
  4. This will be important to make setbrightness a scriptable program.
  5. Copyright 2022 kzimmermann - https://tilde.town/~kzimmermann
  6. Licensed under the GNU GPL v3 - https://www.gnu.org/licenses
  7. */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. // datatype of a "tuple" of a leading character and a numerical value:
  11. struct argtuple {
  12. char sign;
  13. int value;
  14. };
  15. // this function will process a token like "+83239" and identify the parts:
  16. struct argtuple
  17. parseArg(char token[])
  18. {
  19. struct argtuple t;
  20. sscanf(token, "%1c%d", &t.sign, &t.value);
  21. if (!(t.sign == '+' || t.sign == '-')) {
  22. // parsing error. Let's use the (!,0) tuple as an error code
  23. printf("Warning: argument does not contain a sign!\n");
  24. t.sign = '!';
  25. t.value = 0;
  26. }
  27. return t;
  28. }
  29. int
  30. main(int argc, char *argv[])
  31. {
  32. if (argc == 1) {
  33. printf("Pass an argument containing a char and an int (+3424, etc)\n");
  34. return 1;
  35. }
  36. struct argtuple at;
  37. for (int i = 1; i < argc; ++i) {
  38. at = parseArg(argv[i]);
  39. if (at.sign == '!' && at.value == 0) {
  40. printf("Error scanning argument #%d.\n", i);
  41. }
  42. else {
  43. printf("Argument #%d: { %c, %d}\n", i, at.sign, at.value);
  44. }
  45. }
  46. return 0;
  47. }