Air Quality Monitor
Portable C application for collecting, storing, and analyzing air quality sensor readings
Loading...
Searching...
No Matches
aqm_platform.c
1#include "core/aqm_platform.h"
2#include <ctype.h>
3#include <errno.h>
4#include <limits.h>
5#include <stdlib.h>
6#include <string.h>
7
8#ifdef _WIN32
9#include <windows.h>
10#include <direct.h>
11#else
12#include <unistd.h>
13#endif
14
15int aqm_mkdir_p(const char *path) {
16 if (!path || !path[0])
17 return -1;
18#ifdef _WIN32
19 if (_mkdir(path) != 0) {
20 DWORD err = GetLastError();
21 if (err != ERROR_ALREADY_EXISTS)
22 return -1;
23 }
24 return 0;
25#else
26 if (mkdir(path, 0755) != 0) {
27 if (errno != EEXIST)
28 return -1;
29 }
30 return 0;
31#endif
32}
33
34void aqm_sleep_seconds(unsigned seconds) {
35#ifdef _WIN32
36 Sleep((DWORD)seconds * 1000U);
37#else
38 sleep(seconds);
39#endif
40}
41
42void aqm_flush_stdin(void) {
43 int c;
44 while ((c = getchar()) != '\n' && c != EOF)
45 ;
46}
47
48int aqm_parse_int(const char *input, int *out) {
49 if (!input || !out)
50 return 0;
51
52 char *endptr = NULL;
53 errno = 0;
54 long value = strtol(input, &endptr, 10);
55 if (endptr == input || errno != 0)
56 return 0;
57 while (*endptr != '\0' && isspace((unsigned char)*endptr))
58 endptr++;
59 if (*endptr != '\0')
60 return 0;
61 if (value < INT_MIN || value > INT_MAX)
62 return 0;
63 *out = (int)value;
64 return 1;
65}
66
67int aqm_parse_float(const char *input, float *out) {
68 if (!input || !out)
69 return 0;
70
71 char *endptr = NULL;
72 errno = 0;
73 float value = strtof(input, &endptr);
74 if (endptr == input || errno != 0)
75 return 0;
76 while (*endptr != '\0' && isspace((unsigned char)*endptr))
77 endptr++;
78 if (*endptr != '\0')
79 return 0;
80 *out = value;
81 return 1;
82}
83
84void aqm_trim_crlf(char *s) {
85 if (!s)
86 return;
87 size_t n = strlen(s);
88 while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r' || isspace((unsigned char)s[n - 1]))) {
89 s[--n] = '\0';
90 }
91}