Arquivos: bloco "leia o arquivo %1" (FS.ReadText)

Le o arquivo inteiro de uma vez e devolve o texto (vazio se nao abrir).
Com isso da para ler .obj/.json direto nos blocos, sem abrir/ler/fechar
na mao; e o que faltava para um leitor de Wavefront .obj em project.json.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude Opus 5 committed 2026-10-29 00:48:48 -03:00
1 parent 67ba86601c
commit bf298ccefa
4 files changed
+41 -4

No files matched your search

+24
View File
@@ -78,6 +78,27 @@ static void eval_read(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
}
static void eval_readtext(TinyBlocks_Block* self, TinyBlocks* rt) {
const char* path = tb_block_input_text(self, rt, 0);
char* buf = NULL;
if (path[0]) {
FILE* f = fopen(path, "rb");
if (f) {
fseek(f, 0, SEEK_END);
long end = ftell(f);
fseek(f, 0, SEEK_SET);
size_t cap = (end > 0) ? (size_t)end : 0;
buf = (char*)malloc(cap + 1);
if (buf) { size_t n = fread(buf, 1, cap, f); buf[n] = 0; }
fclose(f);
}
}
TinyBlocks_Value v = tb_value_text(buf ? buf : "");
free(buf);
tb_block_set_output(self, 0, v);
self->dirty = false;
}
static void eval_write(TinyBlocks_Block* self, TinyBlocks* rt) {
FILE* f = fs_get(in_int(self, rt, 0));
const char* text = tb_block_input_text(self, rt, 1);
@@ -244,6 +265,8 @@ static bool fs_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
static const TinyBlocks_SlotDesc isdir_out[] = {{"é pasta?", TB_VALUE_INTEGER}};
static const TinyBlocks_SlotDesc exist_out[] = {{"existe?", TB_VALUE_INTEGER}};
TB_BLOCK_META("FS.ReadText", "eval_readtext",
"Le o arquivo inteiro de uma vez e devolve o texto (vazio se nao abrir)");
TB_BLOCK_META("FS.ListDir", "eval_listdir",
"Lista com os nomes dos itens da pasta (ordem alfabetica)");
TB_BLOCK_META("FS.ListCount", "eval_listcount",
@@ -259,6 +282,7 @@ static bool fs_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
return reg(rt, lib, "FS.Open", open_in, 1, handle_out, 1, eval_open)
&& reg(rt, lib, "FS.Read", read_in, 2, text_out, 1, eval_read)
&& reg(rt, lib, "FS.ReadText", path_in, 1, text_out, 1, eval_readtext)
&& reg(rt, lib, "FS.Write", write_in, 2, NULL, 0, eval_write)
&& reg(rt, lib, "FS.Append", append_in, 2, NULL, 0, eval_append)
&& reg(rt, lib, "FS.Tell", tell_in, 1, pos_out, 1, eval_tell)