|
- static const char *TAG = "utils";
- #include <esp_log.h>
-
- #include <sys/time.h>
- #include <cstring>
-
- #include "utils.hpp"
-
-
- int64_t time_us() {
- /*struct timeval tv_now;
- gettimeofday(&tv_now, NULL);
- return (int64_t)tv_now.tv_sec * 1000000L + (int64_t)tv_now.tv_usec;*/
- struct timespec ts;
- clock_gettime(CLOCK_MONOTONIC, &ts);
- return (int64_t)ts.tv_sec * 1000000L + (int64_t)ts.tv_nsec / 1000L;
- }
-
-
-
- std::string read_file(const char *path) {
- std::string data;
- FILE *f = fopen(path, "r");
- if (!f) {
- ESP_LOGE(TAG, "Failed to read %s", path);
- return data;
- }
- constexpr size_t szbuf = 4096;
- char *buf = (char*)malloc(szbuf);
- size_t nread;
- while ((nread = fread(buf, 1, szbuf - 1, f)) > 0) {
- buf[nread] = '\0';
- data += buf;
- }
- fclose(f);
- free(buf);
- return data;
- }
-
- void write_file(const char *path, const std::string &data) {
- return write_file(path, data.c_str(), data.length());
- }
-
- void write_file(const char *path, const char *data, int len) {
- FILE *f = fopen(path, "w");
- if (!f) {
- ESP_LOGE(TAG, "Failed to open %s", path);
- return;
- }
- const char *ptr = data;
- size_t remain = (len < 0 ? strlen(data) : len);
- size_t nwritten = fwrite(ptr, 1, remain, f);
- if (nwritten != remain) {
- ESP_LOGE(TAG, "Failed to write to %s: %d/%d", path, nwritten, remain);
- }
- fclose(f);
- }
|