fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. typedef struct emp {
  6. char *name;
  7. char *forename;
  8. char *job;
  9. char *zipcode;
  10. int id;
  11. struct emp *next;
  12. } t_emp;
  13.  
  14. //For strdup is not a standard
  15. char *strdup(const char *s){
  16. char *ret = malloc(strlen(s)+1);
  17. if(ret)
  18. strcpy(ret, s);
  19. return ret;
  20. }
  21.  
  22. t_emp *read_func(FILE *fp){
  23. static const char *delim = " \t\n";
  24. char line[256];
  25.  
  26. while (fgets(line, sizeof(line), fp)){
  27. char *str = strtok(line, delim);
  28. if(!str || strcmp(str, "new_employee") != 0)
  29. continue;
  30. t_emp *emp = malloc(sizeof(*emp));//check omitted
  31. emp->name = strdup(strtok(NULL, delim));//check omitted
  32. emp->forename = strdup(strtok(NULL, delim));
  33. emp->job = strdup(strtok(NULL, delim));
  34. emp->zipcode = strdup(strtok(NULL, delim));
  35. emp->id = atoi(strtok(NULL, delim));
  36. emp->next = NULL;
  37. return emp;
  38. }
  39. return NULL;
  40. }
  41.  
  42. void fill_struct(t_emp *s_emp){
  43. FILE *fp = stdin;
  44. while(NULL!= (s_emp->next = read_func(fp)))
  45. s_emp = s_emp->next;
  46. }
  47.  
  48. void print_emp(t_emp *s_emp){
  49. while (s_emp != NULL){
  50. printf("******************************\n");
  51. printf("%s %s\n", s_emp->forename, s_emp->name);
  52. printf("position: %s\n", s_emp->job);
  53. printf("city: %s\n", s_emp->zipcode);
  54. s_emp = s_emp->next;
  55. }
  56. }
  57.  
  58. int main(void){
  59. t_emp s_emp = { .next = NULL };//list holder, this is dummy.
  60.  
  61. fill_struct(&s_emp);
  62. print_emp(s_emp.next);
  63. //release list
  64. }
Success #stdin #stdout 0s 9432KB
stdin
new_employee Hasselhoff David PDG F-13000 1 
new_employee Anderson Pamela DDR F-31000 2 
new_employee LeeNolin Gena DDR F-94270 3
new_employee Charvet David DPR F-54000 4
stdout
******************************
David Hasselhoff
position: PDG
city: F-13000
******************************
Pamela Anderson
position: DDR
city: F-31000
******************************
Gena LeeNolin
position: DDR
city: F-94270
******************************
David Charvet
position: DPR
city: F-54000