archeus/src/std/io.c

93 lines
2.7 KiB
C
Raw Normal View History

2022-10-27 15:16:54 -06:00
#include "arc/std/io.h"
#include "arc/std/errno.h"
#include "arc/std/string.h"
2022-10-27 15:16:54 -06:00
#include <stdio.h>
#include <stdlib.h>
2024-01-27 03:14:04 -07:00
void ARC_IO_ReadFileToUint8t(ARC_String *path, uint8_t **data, uint64_t *length){
FILE *file = fopen(path->data, "rb");
if(!file){
arc_errno = ARC_ERRNO_NULL;
ARC_DEBUG_LOG(arc_errno, "ARC_IO_FileToStr(ARC_String *path, ARC_String **data), could not open file \"%s\"", path->data);
*length = 0;
*data = NULL;
return;
}
fseek(file, 0L, SEEK_END);
*length = ftell(file);
rewind(file);
*data = (uint8_t *) calloc(1, *length + 1);
if(*data == NULL){
fclose(file);
arc_errno = ARC_ERRNO_NULL;
ARC_DEBUG_ERR("ARC_IO_FileToStr(ARC_String *path, ARC_String **data), file data is NULL");
*length = 0;
return;
}
if(1 != fread(*data, *length, 1, file)){
fclose(file);
arc_errno = ARC_ERRNO_COPY;
ARC_DEBUG_ERR("ARC_IO_FileToStr(ARC_String *path, ARC_String **data), could not copy file data");
*length = 0;
*data = NULL;
return;
}
fclose(file);
}
void ARC_IO_FileToStr(ARC_String *path, ARC_String **data){
FILE *file = fopen(path->data, "rb");
if(!file){
arc_errno = ARC_ERRNO_NULL;
2024-01-23 21:16:43 -07:00
ARC_DEBUG_LOG(arc_errno, "ARC_IO_FileToStr(ARC_String *path, ARC_String **data), could not open file \"%s\"", path->data);
2024-01-12 19:48:06 -07:00
return;
}
2022-10-27 15:16:54 -06:00
fseek(file, 0L, SEEK_END);
uint64_t length = ftell(file);
rewind(file);
2022-10-27 15:16:54 -06:00
char *fileData = (char *) calloc(1, length + 1);
if(fileData == NULL){
fclose(file);
arc_errno = ARC_ERRNO_NULL;
2024-01-23 21:16:43 -07:00
ARC_DEBUG_ERR("ARC_IO_FileToStr(ARC_String *path, ARC_String **data), file data is NULL");
*data = NULL;
return;
}
2022-10-27 15:16:54 -06:00
if(1 != fread(fileData, length, 1, file)){
fclose(file);
arc_errno = ARC_ERRNO_COPY;
2024-01-23 21:16:43 -07:00
ARC_DEBUG_ERR("ARC_IO_FileToStr(ARC_String *path, ARC_String **data), could not copy file data");
*data = NULL;
return;
}
2022-10-27 15:16:54 -06:00
fclose(file);
ARC_String_Create(data, fileData, length);
free(fileData);
2022-10-27 15:16:54 -06:00
}
2024-01-23 21:16:43 -07:00
void ARC_IO_WriteStrToFile(ARC_String *path, ARC_String *data){
FILE *file = fopen(path->data, "wb");
if(!file){
arc_errno = ARC_ERRNO_NULL;
ARC_DEBUG_LOG(arc_errno, "ARC_IO_WriteStrToFile(ARC_String *path, ARC_String *data), could not open file \"%s\"", path->data);
return;
}
if(1 != fwrite(data->data, data->length, 1, file)){
fclose(file);
arc_errno = ARC_ERRNO_COPY;
ARC_DEBUG_ERR("ARC_IO_WriteStrToFile(ARC_String *path, ARC_String **data), could not write file data");
return;
}
fclose(file);
}