posixfs.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #include <stdio.h>
  2. #include "minilisp.h"
  3. #include "alloc.h"
  4. #include "stream.h"
  5. #include "compiler_new.h"
  6. #include <sys/stat.h>
  7. #include <unistd.h>
  8. #include <fcntl.h>
  9. #include <dirent.h>
  10. Cell* _file_cell;
  11. Cell* posixfs_open(Cell* cpath) {
  12. char* path;
  13. _file_cell = alloc_nil();
  14. if (!cpath || cpath->tag!=TAG_STR) {
  15. printf("[posixfs] open error: non-string path given\r\n");
  16. return _file_cell;
  17. }
  18. path = cpath->ar.addr;
  19. if (!strncmp(path,"/sd/",4)) {
  20. char* filename = NULL;
  21. if (strlen(path)>4) {
  22. filename = path+4;
  23. }
  24. if (!filename || !filename[0]) filename = ".";
  25. //printf("filename: %s\r\n",filename);
  26. if (filename) {
  27. struct stat src_stat;
  28. DIR* dirp;
  29. int f;
  30. off_t len;
  31. if (stat(filename, &src_stat)) {
  32. _file_cell = alloc_string_copy("<file not found>");
  33. return _file_cell;
  34. }
  35. len = src_stat.st_size;
  36. if ((dirp = opendir(filename))) {
  37. struct dirent *dp;
  38. Cell* nl = alloc_string_copy("\n");
  39. _file_cell = alloc_string_copy("");
  40. do {
  41. if ((dp = readdir(dirp)) != NULL) {
  42. printf("dp: |%s|\r\n",dp->d_name);
  43. _file_cell = alloc_concat(_file_cell,alloc_concat(alloc_string_copy(dp->d_name),nl));
  44. }
  45. } while (dp != NULL);
  46. return _file_cell;
  47. }
  48. f = open(filename, O_RDONLY);
  49. if (f>-1) {
  50. Cell* res;
  51. printf("[posixfs] trying to read file of len %zu...\r\n",len);
  52. res = alloc_num_bytes(len);
  53. read(f, res->ar.addr, len);
  54. close(f);
  55. // TODO: close?
  56. _file_cell = res;
  57. return res;
  58. } else {
  59. // TODO should return error
  60. printf("[posixfs] could not open file :(\r\n");
  61. _file_cell = alloc_string_copy("<error: couldn't open file.>"); // FIXME hack
  62. return _file_cell;
  63. }
  64. _file_cell = alloc_string_copy("<error: file not found.>");
  65. return _file_cell;
  66. } else {
  67. // TODO dir
  68. }
  69. }
  70. return _file_cell;
  71. }
  72. Cell* posixfs_read(Cell* stream) {
  73. return _file_cell;
  74. }
  75. Cell* posixfs_write(Cell* arg) {
  76. return NULL;
  77. }
  78. Cell* posixfs_mmap(Cell* arg) {
  79. return alloc_nil();
  80. }
  81. void mount_posixfs() {
  82. fs_mount_builtin("/sd", posixfs_open, posixfs_read, posixfs_write, 0, posixfs_mmap);
  83. }