Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. TB newTB(char *text) {
  2. // Intializing textbuffer
  3. TB new = malloc(sizeof(struct textbuffer));
  4. new->size = 0;
  5. new->head = NULL;
  6. new->tail = NULL;
  7. // Checking for error cases
  8. if (text == NULL) {
  9. printf("Error! Empty text provided.\n");
  10. abort();
  11. }
  12. if (text[0] == '\0') {
  13. return new;
  14. }
  15. // Defining pointers
  16. struct node *curr = NULL;
  17. struct node *temp = NULL;
  18. int offset = 0;
  19. // While the text hasnt reached null terminator
  20. while (text[offset] != '\0') {
  21. // Allocate space for a new node
  22. struct node *newNode = malloc(sizeof(*newNode));
  23. char *words = split(text, offset);
  24. offset = offset + strlen(words) + 1;
  25. // For the very first node in the tb
  26. if (new->head == NULL) {
  27. // Localises string
  28. newNode->line = malloc(sizeof(char) * strlen(words) + 1);
  29. strcpy(newNode->line, words);
  30. newNode->prev = NULL;
  31. newNode->next = NULL;
  32. new->head = newNode;
  33. new->tail = newNode;
  34. new->size = 1;
  35. curr = new->head;
  36. }
  37. // For all other nodes
  38. else {
  39. newNode->line = malloc(sizeof(char) * strlen(words) + 1);
  40. strcpy(newNode->line, words);
  41. newNode->next = NULL;
  42. newNode->prev = curr;
  43. curr->next = newNode;
  44. temp = curr;
  45. curr = curr->next;
  46. curr->prev = temp;
  47. new->tail = curr;
  48. new->size++;
  49. }
  50. free(words);
  51. }
  52. return new;
  53. }
  54.  
  55. // Split function that tokenises the string
  56. static char *split(char *string, int offset) {
  57. int counter = offset;
  58. int counter1 = 0;
  59. char *splitWords = calloc(strlen(string), sizeof(char));
  60. while (string[counter] != '\n') {
  61. splitWords[counter1] = string[counter];
  62. counter++;
  63. counter1++;
  64. }
  65. return splitWords;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement