helpers.c 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #include "helpers.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <sys/types.h>
  6. #include <dirent.h>
  7. bool light_file_read_val(char const *filename, unsigned long *val)
  8. {
  9. FILE *fp;
  10. unsigned long data;
  11. fp = fopen(filename, "r");
  12. if (!fp) {
  13. LIGHT_PERMERR("reading");
  14. return false;
  15. }
  16. if (fscanf(fp, "%lu", &data) != 1) {
  17. LIGHT_ERR("Couldn't parse a positive integer number from '%s'", filename);
  18. fclose(fp);
  19. return false;
  20. }
  21. *val = data;
  22. fclose(fp);
  23. return true;
  24. }
  25. bool light_file_write_val(char const *filename, unsigned long val)
  26. {
  27. FILE *fp;
  28. fp = fopen(filename, "w");
  29. if (!fp) {
  30. LIGHT_PERMERR("writing");
  31. return false;
  32. }
  33. if (fprintf(fp, "%lu", val) < 0) {
  34. LIGHT_ERR("fprintf failed");
  35. fclose(fp);
  36. return false;
  37. }
  38. fclose(fp);
  39. return true;
  40. }
  41. /* Returns true if file is writable, false otherwise */
  42. bool light_file_is_writable(char const *filename)
  43. {
  44. FILE *fp;
  45. fp = fopen(filename, "r+");
  46. if (!fp) {
  47. LIGHT_PERMWARN("writing");
  48. return false;
  49. }
  50. fclose(fp);
  51. return true;
  52. }
  53. /* Returns true if file is readable, false otherwise */
  54. bool light_file_is_readable(char const *filename)
  55. {
  56. FILE *fp;
  57. fp = fopen(filename, "r");
  58. if (!fp) {
  59. LIGHT_PERMWARN("reading");
  60. return false;
  61. }
  62. fclose(fp);
  63. return true;
  64. }
  65. /* Prints a notice about a value which was below `x` and was adjusted to it */
  66. unsigned long light_log_clamp_min(unsigned long min)
  67. {
  68. LIGHT_NOTE("too small value, adjusting to mininum %lu (raw)", min);
  69. return min;
  70. }
  71. /* Prints a notice about a value which was above `x` and was adjusted to it */
  72. unsigned long light_log_clamp_max(unsigned long max)
  73. {
  74. LIGHT_NOTE("too large value, adjusting to mavalimum %lu (raw)", max);
  75. return max;
  76. }
  77. /* Clamps the `percent` value between 0% and 100% */
  78. double light_percent_clamp(double val)
  79. {
  80. if (val < 0.0) {
  81. LIGHT_WARN("specified value %g%% is not valid, adjusting it to 0%%", val);
  82. return 0.0;
  83. }
  84. if (val > 100.0) {
  85. LIGHT_WARN("specified value %g%% is not valid, adjusting it to 100%%", val);
  86. return 100.0;
  87. }
  88. return val;
  89. }