Guest User

Untitled

a guest
Oct 15th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. typedef struct node{ //Linked List Node
  6. char *firstname;
  7. char *lastname;
  8. struct node *next;
  9. }node;
  10.  
  11. void add(node **head, char* fnme, char* lnme){ //Function for adding to
  12. node *new_node; //the linked list
  13. new_node = (node*)malloc(sizeof(node));
  14. if(new_node == NULL){
  15. printf("Error");
  16. return;
  17. }
  18. new_node->firstname = (char*)malloc(100*sizeof(char));
  19. if(new_node->firstname == NULL){
  20. printf("Error");
  21. return;
  22. }
  23. new_node->lastname = (char*)malloc(100*sizeof(char));
  24. if(new_node->lastname == NULL){
  25. printf("Error");
  26. return;
  27. }
  28.  
  29. strcpy(new_node->firstname, fnme);
  30. strcpy(new_node->lastname, lnme);
  31.  
  32. if (*head == NULL){
  33. *head = new_node;
  34. new_node->next = NULL;
  35. return;
  36. }
  37.  
  38. node *current;
  39. current = *head;
  40.  
  41. while(current->next != NULL){
  42. current = current->next;
  43. }
  44.  
  45. current->next = new_node;
  46. new_node->next = NULL;
  47. }
  48.  
  49. void print(node *head){ //Function for printing the list
  50. node *current;
  51. current = head;
  52.  
  53. while(current != NULL){
  54. printf("%s %sn", current->firstname, current->lastname);
  55. current = current->next;
  56. }
  57. }
  58.  
  59. int main() {
  60.  
  61. node *head = NULL;
  62. char character;
  63.  
  64. FILE *fp;
  65. fp = fopen("input.txt", "r");
  66.  
  67. while ((character = fgetc(fp)) != EOF) {
  68. char *fnme, *lnme;
  69. fnme = (char*)malloc(100 * sizeof(char));
  70. if(fnme == NULL){
  71. printf("Error");
  72. return -1;
  73. }
  74. lnme = (char*)malloc(100 * sizeof(char));
  75. if(lnme == NULL){
  76. printf("Error");
  77. return -1;
  78. }
  79.  
  80. int i = 0;
  81. while (character != ' ') { //Reading the letters until the
  82. fnme[i++] = character; //first space (first name)
  83. character = fgetc(fp);
  84. }
  85. fnme[++i] = '';
  86.  
  87. i = 0;
  88. while (character != 'n') { //Reading the letters until
  89. lnme[i++] = character; //new line (last name)
  90. character = fgetc(fp);
  91. }
  92. lnme[++i] = '';
  93.  
  94. add(&head, fnme, lnme); //adding the names to the linked list
  95.  
  96. free(fnme);
  97. free(lnme);
  98. }
  99.  
  100. print(head); //printing the list
  101. return 0;
  102. }
Add Comment
Please, Sign In to add comment