2026-01-02 20:53:07 +11:00
|
|
|
#include <stdio.h>
|
|
|
|
|
#include <stdlib.h>
|
|
|
|
|
#include "groundext.h"
|
|
|
|
|
|
|
|
|
|
GroundValue native_file_read(GroundScope* scope, List args) {
|
|
|
|
|
if (args.size < 1 || args.values[0].type != STRING) {
|
|
|
|
|
return groundCreateValue(NONE);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
char* path = args.values[0].data.stringVal;
|
|
|
|
|
FILE* f = fopen(path, "r");
|
|
|
|
|
if (!f) {
|
2026-01-18 21:37:46 +11:00
|
|
|
ERROR("Failed to open file for reading", "FileError");
|
2026-01-02 20:53:07 +11:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fseek(f, 0, SEEK_END);
|
|
|
|
|
long fsize = ftell(f);
|
|
|
|
|
fseek(f, 0, SEEK_SET);
|
|
|
|
|
|
|
|
|
|
char* content = malloc(fsize + 1);
|
|
|
|
|
if (!content) {
|
|
|
|
|
fclose(f);
|
2026-01-18 21:37:46 +11:00
|
|
|
ERROR("Failed to allocate memory for file reading", "FileError");
|
2026-01-02 20:53:07 +11:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fread(content, 1, fsize, f);
|
|
|
|
|
fclose(f);
|
|
|
|
|
content[fsize] = 0;
|
|
|
|
|
|
|
|
|
|
GroundValue val = groundCreateValue(STRING, content);
|
|
|
|
|
free(content);
|
|
|
|
|
return val;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
GroundValue native_file_write(GroundScope* scope, List args) {
|
|
|
|
|
if (args.size < 2 || args.values[0].type != STRING || args.values[1].type != STRING) {
|
|
|
|
|
return groundCreateValue(BOOL, 0);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
char* path = args.values[0].data.stringVal;
|
|
|
|
|
char* content = args.values[1].data.stringVal;
|
|
|
|
|
|
|
|
|
|
FILE* f = fopen(path, "w");
|
|
|
|
|
if (!f) {
|
2026-01-18 21:37:46 +11:00
|
|
|
ERROR("Failed to open file for writing", "FileError");
|
2026-01-02 20:53:07 +11:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fprintf(f, "%s", content);
|
|
|
|
|
fclose(f);
|
|
|
|
|
|
|
|
|
|
return groundCreateValue(BOOL, 1);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ground_init(GroundScope* scope) {
|
|
|
|
|
groundAddNativeFunction(scope, "file_Read", native_file_read, STRING, 1, STRING, "path");
|
|
|
|
|
groundAddNativeFunction(scope, "file_Write", native_file_write, BOOL, 2, STRING, "path", STRING, "content");
|
|
|
|
|
}
|