/* * TinyBlocks - tb_fs.c * Categoria "Arquivos": abra / leia / escreva / anexe / posicao, listar * pasta (FS.ListDir/ListCount/ListItem) e testes FS.IsFile/IsDir/Exists. * Mantem uma pequena tabela de arquivos abertos (handle inteiro >= 1). */ #define _POSIX_C_SOURCE 200809L #include #include #include #include #include #include #include #include #include #include "tb_fs.h" #define FS_MAX_FILES 64 static FILE* s_files[FS_MAX_FILES]; static int fs_slot(void) { for (int i = 0; i < FS_MAX_FILES; i++) if (!s_files[i]) return i; return -1; } static FILE* fs_get(int64_t handle) { int i = (int)handle - 1; if (i < 0 || i >= FS_MAX_FILES) return NULL; return s_files[i]; } static void fs_close_slot(int i) { if (i >= 0 && i < FS_MAX_FILES && s_files[i]) { fclose(s_files[i]); s_files[i] = NULL; } } static int64_t in_int(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { TinyBlocks_Value v = tb_block_get_input(self, rt, i); if (v.kind == TB_VALUE_INTEGER) return v.as.integer; if (v.kind == TB_VALUE_REAL) return (int64_t)v.as.real; return 0; } static void eval_open(TinyBlocks_Block* self, TinyBlocks* rt) { const char* path = tb_block_input_text(self, rt, 0); int slot = fs_slot(); int64_t handle = 0; if (slot >= 0 && path[0]) { FILE* f = fopen(path, "rb"); if (f) { s_files[slot] = f; handle = slot + 1; } } tb_block_set_output(self, 0, tb_value_integer(handle)); self->dirty = false; } static void eval_read(TinyBlocks_Block* self, TinyBlocks* rt) { FILE* f = fs_get(in_int(self, rt, 0)); int64_t want = in_int(self, rt, 1); char* buf = NULL; size_t n = 0; if (f) { long start = ftell(f); fseek(f, 0, SEEK_END); long end = ftell(f); fseek(f, start, SEEK_SET); size_t avail = (end > start) ? (size_t)(end - start) : 0; if (want > 0 && (size_t)want < avail) avail = (size_t)want; buf = (char*)malloc(avail + 1); if (buf) { n = fread(buf, 1, avail, f); buf[n] = 0; } } 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); if (f) fwrite(text, 1, strlen(text), f); self->dirty = false; } static void eval_append(TinyBlocks_Block* self, TinyBlocks* rt) { const char* path = tb_block_input_text(self, rt, 0); const char* text = tb_block_input_text(self, rt, 1); if (path[0]) { FILE* f = fopen(path, "ab"); if (f) { fwrite(text, 1, strlen(text), f); fclose(f); } } self->dirty = false; } static void eval_tell(TinyBlocks_Block* self, TinyBlocks* rt) { FILE* f = fs_get(in_int(self, rt, 0)); long pos = f ? ftell(f) : -1; tb_block_set_output(self, 0, tb_value_integer(pos)); self->dirty = false; } static void eval_close(TinyBlocks_Block* self, TinyBlocks* rt) { int64_t h = in_int(self, rt, 0); fs_close_slot((int)h - 1); self->dirty = false; } /* -- Pastas --- */ static int cmp_name(const void* a, const void* b) { return strcasecmp(*(char* const*)a, *(char* const*)b); } /* Nomes da pasta (sem "." e ".."), em ordem alfabetica. Vazio = pasta atual. Devolve um vetor alocado (libere com free_names) e o total. */ static char** list_names(const char* path, int* count) { *count = 0; DIR* d = opendir(path[0] ? path : "."); if (!d) return NULL; char** v = NULL; int n = 0, cap = 0; struct dirent* de; while ((de = readdir(d)) != NULL) { if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue; if (n == cap) { int nc = cap ? cap * 2 : 32; char** nv = realloc(v, (size_t)nc * sizeof(char*)); if (!nv) break; v = nv; cap = nc; } size_t len = strlen(de->d_name); char* copy = malloc(len + 1); if (!copy) break; memcpy(copy, de->d_name, len + 1); v[n++] = copy; } closedir(d); if (n > 1) qsort(v, (size_t)n, sizeof(char*), cmp_name); *count = n; return v; } static void free_names(char** v, int n) { for (int i = 0; i < n; i++) free(v[i]); free(v); } static void eval_listdir(TinyBlocks_Block* self, TinyBlocks* rt) { int n = 0; char** names = list_names(tb_block_input_text(self, rt, 0), &n); TinyBlocks_JsonValue* arr = tb_json_array(); for (int i = 0; arr && i < n; i++) { TinyBlocks_JsonValue* s = tb_json_string(names[i]); if (s) { tb_json_array_push(arr, s); tb_json_release(s); } } free_names(names, n); tb_block_set_output(self, 0, tb_value_json(arr)); tb_json_release(arr); self->dirty = false; } static void eval_listcount(TinyBlocks_Block* self, TinyBlocks* rt) { int n = 0; char** names = list_names(tb_block_input_text(self, rt, 0), &n); free_names(names, n); tb_block_set_output(self, 0, tb_value_integer(n)); self->dirty = false; } /* item N (1..total) da pasta, em ordem alfabetica; fora da faixa = "" */ static void eval_listitem(TinyBlocks_Block* self, TinyBlocks* rt) { int n = 0; char** names = list_names(tb_block_input_text(self, rt, 0), &n); int64_t k = in_int(self, rt, 1); const char* item = (k >= 1 && k <= n) ? names[k - 1] : ""; tb_block_set_output(self, 0, tb_value_text(item)); free_names(names, n); self->dirty = false; } static void eval_isfile(TinyBlocks_Block* self, TinyBlocks* rt) { struct stat st; const char* p = tb_block_input_text(self, rt, 0); bool ok = p[0] && stat(p, &st) == 0 && S_ISREG(st.st_mode); tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0)); self->dirty = false; } static void eval_isdir(TinyBlocks_Block* self, TinyBlocks* rt) { struct stat st; const char* p = tb_block_input_text(self, rt, 0); bool ok = p[0] && stat(p, &st) == 0 && S_ISDIR(st.st_mode); tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0)); self->dirty = false; } static void eval_exists(TinyBlocks_Block* self, TinyBlocks* rt) { struct stat st; const char* p = tb_block_input_text(self, rt, 0); bool ok = p[0] && stat(p, &st) == 0; tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0)); self->dirty = false; } /* -- Registro --- */ static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, const TinyBlocks_SlotDesc* in, uint32_t ni, const TinyBlocks_SlotDesc* out, uint32_t no, void (*fn)(TinyBlocks_Block*, TinyBlocks*)) { TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn); return t && tb_library_add(lib, &t->base); } static bool fs_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static const TinyBlocks_Category cat = { "Arquivos", { 0/255.f, 188/255.f, 212/255.f, 1.f}, { 0/255.f, 151/255.f, 167/255.f, 1.f}, }; tb_library_set_category(lib, &cat); static const TinyBlocks_SlotDesc open_in[] = {{"nome", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc read_in[] = {{"arquivo", TB_VALUE_INTEGER}, {"bytes", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc write_in[] = {{"arquivo", TB_VALUE_INTEGER}, {"texto", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc append_in[] = {{"nome", TB_VALUE_TEXT}, {"texto", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc tell_in[] = {{"arquivo", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc close_in[] = {{"arquivo", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc handle_out[]= {{"handle", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc text_out[] = {{"texto", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc pos_out[] = {{"posicao",TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc dir_in[] = {{"pasta", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc item_in[] = {{"pasta", TB_VALUE_TEXT}, {"numero", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc path_in[] = {{"caminho", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc list_out[] = {{"lista", TB_VALUE_JSON}}; static const TinyBlocks_SlotDesc count_out[] = {{"quantidade", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc name_out[] = {{"nome", TB_VALUE_TEXT}}; /* saida terminada em '?' = bloco booleano (hexagonal no editor) */ static const TinyBlocks_SlotDesc file_out[] = {{"é arquivo?", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc isdir_out[] = {{"é pasta?", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc exist_out[] = {{"existe?", TB_VALUE_INTEGER}}; TB_BLOCK_META("FS.ListDir", "eval_listdir", "Lista com os nomes dos itens da pasta (ordem alfabetica)"); TB_BLOCK_META("FS.ListCount", "eval_listcount", "Quantos itens (arquivos e pastas) a pasta tem"); TB_BLOCK_META("FS.ListItem", "eval_listitem", "Nome do item N da pasta (1 = primeiro, ordem alfabetica)"); TB_BLOCK_META("FS.IsFile", "eval_isfile", "Verdadeiro se o caminho for um arquivo"); TB_BLOCK_META("FS.IsDir", "eval_isdir", "Verdadeiro se o caminho for uma pasta"); TB_BLOCK_META("FS.Exists", "eval_exists", "Verdadeiro se o caminho existir (arquivo ou pasta)"); 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.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) && reg(rt, lib, "FS.Close", close_in, 1, NULL, 0, eval_close) && reg(rt, lib, "FS.ListDir", dir_in, 1, list_out, 1, eval_listdir) && reg(rt, lib, "FS.ListCount", dir_in, 1, count_out, 1, eval_listcount) && reg(rt, lib, "FS.ListItem", item_in, 2, name_out, 1, eval_listitem) && reg(rt, lib, "FS.IsFile", path_in, 1, file_out, 1, eval_isfile) && reg(rt, lib, "FS.IsDir", path_in, 1, isdir_out, 1, eval_isdir) && reg(rt, lib, "FS.Exists", path_in, 1, exist_out, 1, eval_exists); } static void fs_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { (void)rt; (void)lib; for (int i = 0; i < FS_MAX_FILES; i++) fs_close_slot(i); } TINYBLOCKS_DEFINE_LIBRARY(fs, "tinyblocks-fs", "1.0.0", fs_init, fs_deinit) const TinyBlocks_LibraryDescriptor* tb_fs_get_library(void) { return &_tb_lib_desc_fs; }