shell_file.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <stdlib.h>
  2. #include <assert.h>
  3. #include "private.h"
  4. /*----------------------------------------------------------- */
  5. int clish_shell_push_file(clish_shell_t * this, const char * fname,
  6. bool_t stop_on_error)
  7. {
  8. FILE *file;
  9. int res;
  10. assert(this);
  11. if (!fname)
  12. return -1;
  13. file = fopen(fname, "r");
  14. if (!file)
  15. return -1;
  16. res = clish_shell_push_fd(this, file, stop_on_error);
  17. if (res)
  18. fclose(file);
  19. return res;
  20. }
  21. /*----------------------------------------------------------- */
  22. int clish_shell_push_fd(clish_shell_t * this, FILE * file,
  23. bool_t stop_on_error)
  24. {
  25. /* Allocate a control node */
  26. clish_shell_file_t *node = malloc(sizeof(clish_shell_file_t));
  27. assert(this);
  28. assert(node);
  29. /* intialise the node */
  30. node->file = file;
  31. node->stop_on_error = stop_on_error;
  32. node->next = this->current_file;
  33. /* put the node at the top of the file stack */
  34. this->current_file = node;
  35. /* now switch the terminal's input stream */
  36. tinyrl__set_istream(this->tinyrl, file);
  37. return 0;
  38. }
  39. /*----------------------------------------------------------- */
  40. int clish_shell_pop_file(clish_shell_t *this)
  41. {
  42. int result = -1;
  43. clish_shell_file_t *node = this->current_file;
  44. if (!node)
  45. return -1;
  46. /* remove the current file from the stack... */
  47. this->current_file = node->next;
  48. /* and close the current file... */
  49. fclose(node->file);
  50. if (node->next) {
  51. /* now switch the terminal's input stream */
  52. tinyrl__set_istream(this->tinyrl, node->next->file);
  53. result = 0;
  54. }
  55. /* and free up the memory */
  56. free(node);
  57. return result;
  58. }
  59. /*----------------------------------------------------------- */