mp_flipper_file_reader.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <stdio.h>
  2. #include <furi.h>
  3. #include <storage/storage.h>
  4. #include <mp_flipper_runtime.h>
  5. #include <mp_flipper_file_reader.h>
  6. #include "mp_flipper_file_helper.h"
  7. typedef struct {
  8. size_t pointer;
  9. FuriString* content;
  10. size_t size;
  11. } FileReaderContext;
  12. inline void* mp_flipper_file_reader_context_alloc(const char* filename) {
  13. FuriString* path = furi_string_alloc_printf("%s", filename);
  14. Storage* storage = furi_record_open(RECORD_STORAGE);
  15. File* file = storage_file_alloc(storage);
  16. FileReaderContext* ctx = NULL;
  17. do {
  18. if(mp_flipper_try_resolve_filesystem_path(path) == MP_FLIPPER_IMPORT_STAT_NO_EXIST) {
  19. mp_flipper_raise_os_error_with_filename(MP_ENOENT, filename);
  20. break;
  21. }
  22. if(!storage_file_open(file, furi_string_get_cstr(path), FSAM_READ, FSOM_OPEN_EXISTING)) {
  23. mp_flipper_raise_os_error_with_filename(MP_ENOENT, filename);
  24. break;
  25. }
  26. ctx = malloc(sizeof(FileReaderContext));
  27. ctx->pointer = 0;
  28. ctx->content = furi_string_alloc();
  29. ctx->size = storage_file_size(file);
  30. char character = '\0';
  31. for(size_t i = 0; i < ctx->size; i++) {
  32. storage_file_read(file, &character, 1);
  33. furi_string_push_back(ctx->content, character);
  34. }
  35. } while(false);
  36. storage_file_free(file);
  37. furi_record_close(RECORD_STORAGE);
  38. furi_string_free(path);
  39. return ctx;
  40. }
  41. inline uint32_t mp_flipper_file_reader_read(void* data) {
  42. FileReaderContext* ctx = data;
  43. if(ctx->pointer >= ctx->size) {
  44. return MP_FLIPPER_FILE_READER_EOF;
  45. }
  46. return furi_string_get_char(ctx->content, ctx->pointer++);
  47. }
  48. void mp_flipper_file_reader_close(void* data) {
  49. FileReaderContext* ctx = data;
  50. furi_string_free(ctx->content);
  51. free(data);
  52. }