stringport.c 947 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "stringport.h"
  4. // from stackoverflow.com/questions/2082743/c-equivalent-to-fstreams-peek
  5. int fpeek(FILE *stream)
  6. {
  7. int c;
  8. c = fgetc(stream);
  9. ungetc(c, stream);
  10. return c;
  11. }
  12. int port_peek(string_port *port)
  13. {
  14. switch(port->kind) {
  15. case STRPORT_CHAR:
  16. return port->text[port->place];
  17. break;
  18. case STRPORT_FILE:
  19. return fpeek(port->fptr);
  20. default:
  21. exit(-1);
  22. }
  23. }
  24. int port_eof(string_port *port)
  25. {
  26. switch(port->kind) {
  27. case STRPORT_CHAR:
  28. return port->text[port->place] == '\0';
  29. break;
  30. case STRPORT_FILE:
  31. return feof(port->fptr);
  32. default:
  33. exit(-1);
  34. }
  35. }
  36. int port_getc(string_port *port)
  37. {
  38. int c;
  39. switch(port->kind) {
  40. case STRPORT_CHAR:
  41. c = port->text[port->place];
  42. if(c != '\0') {
  43. port->place++;
  44. }
  45. return c;
  46. case STRPORT_FILE:
  47. return fgetc(port->fptr);
  48. default:
  49. exit(-1);
  50. }
  51. }