lfs_cfg.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Simple config parser
  3. *
  4. * Copyright (c) 2017 Christopher Haster
  5. * Distributed under the MIT license
  6. */
  7. #ifndef LFS_CFG_H
  8. #define LFS_CFG_H
  9. #include <stddef.h>
  10. #include <stdbool.h>
  11. #include <unistd.h>
  12. // This is a simple parser for config files
  13. //
  14. // The cfg file format is dumb simple. Attributes are
  15. // key value pairs separated by a single colon. Delimited
  16. // by comments (#) and newlines (\r\n) and trims
  17. // whitespace ( \t\v\f)
  18. //
  19. // Here's an example file
  20. // # Here is a dump example
  21. // looky: it's_an_attribute
  22. // hey_look: another_attribute
  23. //
  24. // huh: yeah_that's_basically_it # basically it
  25. // Internal config structure
  26. typedef struct lfs_cfg {
  27. size_t len;
  28. size_t size;
  29. size_t blen;
  30. size_t bsize;
  31. char *buf;
  32. struct lfs_cfg_attr {
  33. unsigned key;
  34. unsigned val;
  35. } *attrs;
  36. } lfs_cfg_t;
  37. // Creates a cfg object and reads in the cfg file from the filename
  38. //
  39. // If the lfs_cfg_read fails, returns a negative value from the underlying
  40. // stdio functions
  41. int lfs_cfg_create(lfs_cfg_t *cfg, const char *filename);
  42. // Destroys the cfg object and frees any used memory
  43. void lfs_cfg_destroy(lfs_cfg_t *cfg);
  44. // Checks if a cfg attribute exists
  45. bool lfs_cfg_has(lfs_cfg_t *cfg, const char *key);
  46. // Retrieves a cfg attribute as a null-terminated string
  47. //
  48. // If the attribute does not exist, returns the string passed as def
  49. const char *lfs_cfg_get(lfs_cfg_t *cfg, const char *key, const char *def);
  50. // Retrieves a cfg attribute parsed as an int
  51. //
  52. // If the attribute does not exist or can't be parsed, returns the
  53. // integer passed as def
  54. ssize_t lfs_cfg_geti(lfs_cfg_t *cfg, const char *name, ssize_t def);
  55. // Retrieves a cfg attribute parsed as an unsigned int
  56. //
  57. // If the attribute does not exist or can't be parsed, returns the
  58. // integer passed as def
  59. size_t lfs_cfg_getu(lfs_cfg_t *cfg, const char *name, size_t def);
  60. #endif