pxl8/src/pxl8_io.c

107 lines
2.5 KiB
C
Raw Normal View History

2025-08-13 15:04:49 -05:00
#include "pxl8_io.h"
pxl8_result pxl8_io_read_file(const char* path, char** content, size_t* size) {
if (!path || !content || !size) return PXL8_ERROR_NULL_POINTER;
FILE* file = fopen(path, "rb");
if (!file) {
return PXL8_ERROR_FILE_NOT_FOUND;
}
fseek(file, 0, SEEK_END);
long file_size = ftell(file);
fseek(file, 0, SEEK_SET);
if (file_size < 0) {
fclose(file);
return PXL8_ERROR_SYSTEM_FAILURE;
}
*content = SDL_malloc(file_size + 1);
if (!*content) {
fclose(file);
return PXL8_ERROR_OUT_OF_MEMORY;
}
size_t bytes_read = fread(*content, 1, file_size, file);
(*content)[bytes_read] = '\0';
*size = bytes_read;
fclose(file);
return PXL8_OK;
}
pxl8_result pxl8_io_write_file(const char* path, const char* content, size_t size) {
if (!path || !content) return PXL8_ERROR_NULL_POINTER;
FILE* file = fopen(path, "wb");
if (!file) {
return PXL8_ERROR_SYSTEM_FAILURE;
}
size_t bytes_written = fwrite(content, 1, size, file);
fclose(file);
return (bytes_written == size) ? PXL8_OK : PXL8_ERROR_SYSTEM_FAILURE;
}
pxl8_result pxl8_io_read_binary_file(const char* path, u8** data, size_t* size) {
return pxl8_io_read_file(path, (char**)data, size);
}
pxl8_result pxl8_io_write_binary_file(const char* path, const u8* data, size_t size) {
return pxl8_io_write_file(path, (const char*)data, size);
}
bool pxl8_io_file_exists(const char* path) {
if (!path) return false;
struct stat st;
return stat(path, &st) == 0;
}
f64 pxl8_io_get_file_modified_time(const char* path) {
if (!path) return 0.0;
struct stat st;
if (stat(path, &st) == 0) {
return st.st_mtime;
}
return 0.0;
}
pxl8_result pxl8_io_create_directory(const char* path) {
if (!path) return PXL8_ERROR_NULL_POINTER;
#ifdef _WIN32
if (mkdir(path) != 0) {
#else
if (mkdir(path, 0755) != 0) {
#endif
return PXL8_ERROR_SYSTEM_FAILURE;
}
return PXL8_OK;
}
void pxl8_io_free_file_content(char* content) {
if (content) {
SDL_free(content);
}
}
void pxl8_io_free_binary_data(u8* data) {
if (data) {
SDL_free(data);
}
}
bool pxl8_key_down(const pxl8_input_state* input, i32 key) {
if (!input || key < 0 || key >= 256) return false;
return input->keys[key];
}
bool pxl8_key_pressed(const pxl8_input_state* input, i32 key) {
if (!input || key < 0 || key >= 256) return false;
return input->keys_pressed[key];
}