#include "cli.h"
uint8_t *read_file(const char *path, size_t *out_len)
{
FILE *f = fopen(path, "rb");
if (!f) { perror(path); return NULL; }
fseek(f, 0, SEEK_END);
long sz = ftell(f);
if (sz < 0) { perror(path); fclose(f); return NULL; }
fseek(f, 0, SEEK_SET);
uint8_t *buf = malloc(sz ? sz : 1);
if (!buf) { fclose(f); return NULL; }
fread(buf, 1, sz, f);
fclose(f);
*out_len = sz;
return buf;
}
char *read_text_file(const char *path)
{
size_t len;
uint8_t *buf = read_file(path, &len);
if (!buf) return NULL;
char *txt = malloc(len + 1);
memcpy(txt, buf, len);
txt[len] = '\0';
free(buf);
return txt;
}
int write_file(const char *path, const uint8_t *data, size_t len)
{
FILE *f = fopen(path, "wb");
if (!f) { perror(path); return 1; }
fwrite(data, 1, len, f);
fclose(f);
return 0;
}
const char *detect_filetype(const char *path)
{
const char *dot = strrchr(path, '.');
if (!dot) return NULL;
if (strcmp(dot, ".json") == 0) return "json";
if (strcmp(dot, ".html") == 0 || strcmp(dot, ".htm") == 0) return "html";
if (strcmp(dot, ".xml") == 0) return "xml";
if (strcmp(dot, ".htmx") == 0) return "xml";
return NULL;
}