fork(4) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #define SIZE 50
  5.  
  6. struct employee
  7. {
  8. char *empname;
  9. char *empid;
  10. int age;
  11. char *addr;
  12. };
  13.  
  14. int main()
  15. {
  16. FILE *fp = NULL;
  17. int i = 0;
  18. struct employee var = {NULL, NULL, 0, NULL};
  19. char line[SIZE] = {0}, *ptr = NULL;
  20.  
  21. /* uncommented in your code - Here reading from stdin instead
  22.  
  23.   // Open file for Reading
  24.   if (NULL == (fp = fopen("file.txt","r")))
  25.   {
  26.   perror("Error while opening the file.\n");
  27.   exit(EXIT_FAILURE);
  28.   }
  29.   */
  30.  
  31. /* Allocate Memory */
  32. var.empname = malloc(SIZE);
  33. var.empid = malloc(SIZE);
  34. var.addr = malloc(SIZE);
  35.  
  36. /* Uncomment Below line - Here Reading from stdin
  37.   while (EOF != fscanf(fp, "%s", line))
  38.   */
  39.  
  40. while (EOF != fscanf(stdin, "%s", line))
  41. {
  42. /* 1. Read each line from the file */
  43. printf("\n\n Read line: %s\n", line);
  44.  
  45. /* 2. Tokenise the read line, using "\" delimiter*/
  46. ptr = strtok(line, "\\");
  47. printf("ptr at :%s\n", ptr);
  48. var.empname = ptr;
  49.  
  50. while (NULL != (ptr = strtok(NULL, "\\")))
  51. {
  52. i++;
  53. printf("=====%d==== ptr: %s\n", i, ptr);
  54.  
  55. /* 3. Store the tokens as per structure members , where (i==0) is first member and so on.. */
  56. if(i == 1)
  57. var.empid = ptr;
  58. else if(i == 2)
  59. var.age = atoi(ptr);
  60. else if (i == 3)
  61. var.addr = ptr;
  62. }
  63. i = 0;
  64. printf("After Reading: EmpName:[%s] EmpId:[%s] Age:[%d] Addr:[%s]\n", var.empname, var.empid, var.age, var.addr);
  65. }
  66.  
  67. //fclose(fp);
  68. return 0;
  69. }
  70.  
  71.  
Success #stdin #stdout 0s 2384KB
stdin
empname1\t001\35\tcity1	
empname2\t002\37\tcity2	
stdout

 Read line:  empname1\t001\35\tcity1
ptr at :empname1
=====1==== ptr: t001
=====2==== ptr: 35
=====3==== ptr: tcity1
After Reading: EmpName:[empname1] EmpId:[t001] Age:[35] Addr:[tcity1]


 Read line:  empname2\t002\37\tcity2
ptr at :empname2
=====1==== ptr: t002
=====2==== ptr: 37
=====3==== ptr: tcity2
After Reading: EmpName:[empname2] EmpId:[t002] Age:[37] Addr:[tcity2]