Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.2 KiB

  1. char *getLine(void);
  2. char *trim(char *phrase);
  3. char *getLine(void) {
  4. const size_t sizeIncrement = 10;
  5. char *buffer = malloc(sizeIncrement);
  6. char *currentPosition = buffer;
  7. size_t maximumLength = sizeIncrement;
  8. size_t length = 0;
  9. int character;
  10. if (currentPosition == NULL) {
  11. return NULL;
  12. }
  13. while (1) {
  14. character =fgetc(stdin);
  15. if (character == '\n') {
  16. break;
  17. }
  18. if (++length >= maximumLength) {
  19. char *newBuffer = (char*) realloc(buffer, maximumLength += sizeIncrement);
  20. if (newBuffer == NULL) {
  21. free(buffer);
  22. return NULL;
  23. }
  24. currentPosition = newBuffer + (currentPosition - buffer);
  25. buffer = newBuffer;
  26. }
  27. *currentPosition++ = character;
  28. }
  29. *currentPosition = '\0';
  30. return buffer;
  31. }
  32. char *trim(char *phrase) {
  33. char *old = phrase;
  34. char *new = phrase;
  35. // skip blank chars
  36. while (*old == ' ') {
  37. old++;
  38. }
  39. while (*old) {
  40. *new = *old;
  41. new++;
  42. old++;
  43. }
  44. // set string end char
  45. *new = 0;
  46. return (char*) realloc(phrase, strlen(phrase) + 1);
  47. }